local H = require "packages/new_heg/util"
local U = require "packages/utility/utility"
local extension = Package:new("ssb_heg")
extension.extensionName = "new_heg_diy"
extension.game_modes_whitelist = { 'mul_heg_mode', 'ex_heg_mode' }

Fk:loadTranslationTable{
  ["ssb_heg"] = "国战-三设吧",
  ["ss_heg"] = "三设",
}


-- 国标
local jianxiong = fk.CreateTriggerSkill{
  name = "jianxiong__xizhicai",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card and player.room:getCardArea(data.card) == Card.Processing
  end,
  on_use = function(self, event, target, player, data)
    player.room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
  end,
}
Fk:addSkill(jianxiong)

local fankui = fk.CreateTriggerSkill{
  name = "fankui__xizhicai",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and data.from and not data.from.dead then
      if data.from == player then
        return #player.player_cards[Player.Equip] > 0
      else
        return not data.from:isNude()
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local from = data.from
    local flag =  from == player and "e" or "he"
    local card = room:askForCardChosen(player, from, flag, self.name)
    room:obtainCard(player.id, card, false, fk.ReasonPrey)
  end
}

local ex__guicai = fk.CreateTriggerSkill{
  name = "ex__guicai__xizhicai",
  anim_type = "control",
  events = {fk.AskForRetrial},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and not player:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local card = room:askForResponse(player, self.name, ".|.|.|hand,equip|.|",
      "#ex__guicai-ask::" .. target.id .. ":" .. data.reason, true)
    if card ~= nil then
      room:doIndicate(player.id, {target.id})
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:retrial(self.cost_data, player, data, self.name)
  end,
}
Fk:addSkill(fankui)
Fk:addSkill(ex__guicai)

local hs__ganglie = fk.CreateTriggerSkill{
  name = "hs__ganglie__xizhicai",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_trigger = function(self, event, target, player, data)
    self:doCost(event, target, player, data)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local from = data.from
    if from and not from.dead then room:doIndicate(player.id, {from.id}) end
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".",
    }
    room:judge(judge)
    if judge.card.color == Card.Red and from and not from.dead then
      room:damage{
        from = player,
        to = from,
        damage = 1,
        skillName = self.name,
      }
    elseif judge.card.color == Card.Black and from and not from:isNude() then
      local cid = room:askForCardChosen(player, from, "he", self.name)
      room:throwCard({cid}, self.name, from, player)
    end
  end
}
Fk:addSkill(hs__ganglie)

local ex__tuxi = fk.CreateTriggerSkill{
  name = "ex__tuxi__xizhicai",
  anim_type = "control",
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.n > 0 and
      table.find(player.room:getOtherPlayers(player), function(p) return not p:isKongcheng() end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room:getOtherPlayers(player, false), function(p)
      return not p:isKongcheng() end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, data.n, "#ex__tuxi-choose:::"..data.n, self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tos = table.simpleClone(self.cost_data)
    room:sortPlayersByAction(tos)
    for _, id in ipairs(tos) do
      local to = room:getPlayerById(id)
      if not (to.dead or to:isKongcheng()) then
        local c = room:askForCardChosen(player, to, "h", self.name)
        room:obtainCard(player, c, false, fk.ReasonPrey)
        if player.dead then break end
      end
    end
    data.n = data.n - #tos
  end,
}
Fk:addSkill(ex__tuxi)

local hs__luoyi__xizhicai = fk.CreateTriggerSkill{
  name = "hs__luoyi__xizhicai",
  anim_type = "offensive",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw
  end,
  on_use = function(self, event, target, player, data)
    player.room:askForDiscard(player, 1, 1, false, self.name, false, nil, "hs__luoyi__xizhicai-ask", false)
  end,
}
local hs__luoyi__xizhicai_trigger = fk.CreateTriggerSkill{
  name = "#hs__luoyi__xizhicai_trigger",
  mute = true,
  events = {fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:usedSkillTimes("hs__luoyi__xizhicai", Player.HistoryTurn) > 0 and
      not data.chain and data.card and (data.card.trueName == "slash" or data.card.name == "duel")
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("hs__luoyi__xizhicai")
    room:notifySkillInvoked(player, "hs__luoyi__xizhicai")
    data.damage = data.damage + 1
  end,
}

hs__luoyi__xizhicai:addRelatedSkill(hs__luoyi__xizhicai_trigger)
Fk:addSkill(hs__luoyi__xizhicai)

local yiji = fk.CreateTriggerSkill{
  name = "hs__yiji__xizhicai",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_use = function(self, event, target, player, data)
    local room = player.room
    local ids = room:getNCards(2)
    while true do
      room:setPlayerMark(player, "hs__yiji_cards", ids)
      local _, ret = room:askForUseActiveSkill(player, "hs__yiji_active", "#hs__yiji-give", true, nil, true)
      room:setPlayerMark(player, "hs__yiji_cards", 0)
      if ret then
        for _, id in ipairs(ret.cards) do
          table.removeOne(ids, id)
        end
        room:moveCardTo(ret.cards, Card.PlayerHand, room:getPlayerById(ret.targets[1]), fk.ReasonGive, self.name, nil, false, player.id)
        if #ids == 0 then break end
        if player.dead then
          room:moveCards({
            ids = ids,
            toArea = Card.DiscardPile,
            moveReason = fk.ReasonJustMove,
            skillName = self.name,
          })
          break
        end
      else
        room:moveCardTo(ids, Player.Hand, player, fk.ReasonGive, self.name, nil, false, player.id)
        break
      end
    end
  end,
}
local tiandu = fk.CreateTriggerSkill{
  name = "tiandu__xizhicai",
  anim_type = "drawcard",
  events = {fk.FinishJudge},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.room:getCardArea(data.card) == Card.Processing
  end,
  on_use = function(self, event, target, player, data)
    player.room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
  end,
}
Fk:addSkill(yiji)
Fk:addSkill(tiandu)

local luoshen = fk.CreateTriggerSkill{
  name = "hs__luoshen__xizhicai",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cardsJudged = {}
    while true do
      local judge = {
        who = player,
        reason = self.name,
        pattern = ".|.|spade,club",
        skipDrop = true,
      }
      room:judge(judge)
      local card = judge.card
      if card.color == Card.Black then
        table.insert(cardsJudged, card)
      elseif room:getCardArea(card) == Card.Processing then
        room:moveCardTo(card, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, nil, true, player.id)
      end
      if card.color ~= Card.Black or player.dead or not room:askForSkillInvoke(player, self.name) then
        break
      end
    end
    cardsJudged = table.filter(cardsJudged, function(c) return room:getCardArea(c.id) == Card.Processing end)
    if #cardsJudged > 0 then
      room:obtainCard(player, table.map(cardsJudged, function(card)
        return card.id
      end), true, fk.ReasonJustMove)
    end
  end,
}

local qingguo = fk.CreateViewAsSkill{
  name = "qingguo__xizhicai",
  anim_type = "defensive",
  pattern = "jink",
  card_filter = function(self, to_select, selected)
    if #selected == 1 then return false end
    return Fk:getCardById(to_select).color == Card.Black
      and Fk:currentRoom():getCardArea(to_select) == Player.Hand
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then
      return nil
    end
    local c = Fk:cloneCard("jink")
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
}
Fk:addSkill(luoshen)
Fk:addSkill(qingguo)

local hs__shensu = fk.CreateTriggerSkill{
  name = "hs__shensu__xizhicai",
  anim_type = "offensive",
  events = {fk.EventPhaseChanging},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and not player:prohibitUse(Fk:cloneCard("slash")) then
      if (data.to == Player.Judge and not player.skipped_phases[Player.Draw]) or data.to == Player.Discard then
        return true
      elseif data.to == Player.Play then
        return not player:isNude()
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local slash = Fk:cloneCard("slash")
    local max_num = slash.skill:getMaxTargetNum(player, slash)
    local targets = {}
    for _, p in ipairs(room:getOtherPlayers(player)) do
      if not player:isProhibited(p, slash) then
        table.insert(targets, p.id)
      end
    end
    if #targets == 0 or max_num == 0 then return end
    if data.to == Player.Judge then
      local tos = room:askForChoosePlayers(player, targets, 1, max_num, "#hs__shensu1-choose", self.name, true)
      if #tos > 0 then
        self.cost_data = {tos}
        return true
      end
    elseif data.to == Player.Play then
      local tos, id = room:askForChooseCardAndPlayers(player, targets, 1, max_num, ".|.|.|.|.|equip", "#hs__shensu2-choose", self.name, true)
      if #tos > 0 and id then
        self.cost_data = {tos, {id}}
        return true
      end
    elseif data.to == Player.Discard then
      local tos = room:askForChoosePlayers(player, targets, 1, max_num, "#hs__shensu3-choose", self.name, true)
      if #tos > 0 then
        self.cost_data = {tos}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if data.to == Player.Judge then
      player:skip(Player.Judge)
      player:skip(Player.Draw)
    elseif data.to == Player.Play then
      player:skip(Player.Play)
      room:throwCard(self.cost_data[2], self.name, player, player)
    elseif data.to == Player.Discard then
      player:skip(Player.Discard)
      player.room:loseHp(player, 1, self.name)
    end

    local slash = Fk:cloneCard("slash")
    slash.skillName = self.name
    room:useCard({
      from = target.id,
      tos = table.map(self.cost_data[1], function(pid) return { pid } end),
      card = slash,
      extraUse = true,
    })
    return true
  end,
}
Fk:addSkill(hs__shensu)

local qiaobian = fk.CreateTriggerSkill{
  name = "qiaobian__xizhicai",
  anim_type = "offensive",
  events = {fk.EventPhaseChanging},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and not player:isKongcheng() and
    data.to > Player.Start and data.to < Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    local phase_name_table = {
      [3] = "phase_judge",
      [4] = "phase_draw",
      [5] = "phase_play",
      [6] = "phase_discard",
    }
    local card = player.room:askForDiscard(player, 1, 1, false, self.name, true, ".", "#qiaobian-invoke:::" .. phase_name_table[data.to], true)
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data, self.name, player, player)
    player:skip(data.to)
    if data.to == Player.Draw then
      local targets = table.map(table.filter(room:getOtherPlayers(player), function(p)
        return not p:isKongcheng() end), Util.IdMapper)
      if #targets > 0 then
        local n = math.min(2, #targets)
        local tos = room:askForChoosePlayers(player, targets, 1, n, "#qiaobian-choose:::"..n, self.name, true)
        if #tos > 0 then
          room:sortPlayersByAction(tos)
          for _, id in ipairs(tos) do
            local p = room:getPlayerById(id)
            if not p:isKongcheng() then
              local card_id = room:askForCardChosen(player, p, "h", self.name)
              room:obtainCard(player, card_id, false, fk.ReasonPrey)
            end
          end
        end
      end
    elseif data.to == Player.Play then
      local targets = room:askForChooseToMoveCardInBoard(player, "#qiaobian-move", self.name, true, nil)
      if #targets ~= 0 then
        targets = table.map(targets, function(id) return room:getPlayerById(id) end)
        room:askForMoveCardInBoard(player, targets[1], targets[2], self.name)
      end
    end
    return true
  end,
}
Fk:addSkill(qiaobian)

local duanliang = fk.CreateViewAsSkill{
  name = "hs__duanliang__xizhicai",
  anim_type = "control",
  pattern = "supply_shortage",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).color == Card.Black and Fk:getCardById(to_select).type ~= Card.TypeTrick
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then
      return nil
    end
    local c = Fk:cloneCard("supply_shortage")
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
  before_use = function(self, player, use)
    local targets = TargetGroup:getRealTargets(use.tos)
    if #targets == 0 then return end
    local room = player.room
    for _, p in ipairs(targets) do
      if player:distanceTo(room:getPlayerById(p)) > 2 then
        room:setPlayerMark(player, "@@hs__duanliang__xizhicai-phase", 1)
      end
    end
  end
}
local duanliang_targetmod = fk.CreateTargetModSkill{
  name = "#hs__duanliang__xizhicai_targetmod",
  distance_limit_func =  function(self, player, skill)
    if player:hasSkill(duanliang) and skill.name == "supply_shortage_skill" then
      return 99
    end
  end,
}
local duanliang_invalidity = fk.CreateInvaliditySkill {
  name = "#hs__duanliang__xizhicai_invalidity",
  invalidity_func = function(self, from, skill)
    return from:getMark("@@hs__duanliang__xizhicai-phase") > 0 and
      skill.name == "hs__duanliang__xizhicai"
  end
}
duanliang:addRelatedSkill(duanliang_targetmod)
duanliang:addRelatedSkill(duanliang_invalidity)
Fk:addSkill(duanliang)

local jushou = fk.CreateTriggerSkill{
  name = "hs__jushou__xizhicai",
  anim_type = "defensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local num = 0
    for _, v in pairs(H.getKingdomPlayersNum(room)) do
      if v and v > 0 then
        num = num + 1
      end
    end
    room:drawCards(player, num, self.name)
    if player.dead then return false end
    local jushou_card
    for _, id in pairs(player:getCardIds(Player.Hand)) do
      local card = Fk:getCardById(id)
      if (card.type == Card.TypeEquip and not player:prohibitUse(card)) or (card.type ~= Card.TypeEquip and not player:prohibitDiscard(card)) then
        jushou_card = card
        break
      end
    end
    if not jushou_card then return end
    local _, ret = room:askForUseActiveSkill(player, "#hs__jushou_select", "#hs__jushou-select", false)
    if ret then
      jushou_card = Fk:getCardById(ret.cards[1])
    end
    if jushou_card then
      if jushou_card.type == Card.TypeEquip then
        room:useCard({
          from = player.id,
          tos = {{player.id}},
          card = jushou_card,
        })
      else
        room:throwCard(jushou_card:getEffectiveId(), self.name, player, player)
      end
    end
    if player.dead then return false end
    if num > 2 then player:turnOver() end
  end,
}
Fk:addSkill(jushou)

local hs__qiangxi = fk.CreateActiveSkill{
  name = "hs__qiangxi__xizhicai",
  anim_type = "offensive",
  max_card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    return Fk:getCardById(to_select).sub_type == Card.SubtypeWeapon
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    if #effect.cards > 0 then
      room:throwCard(effect.cards, self.name, player)
    else
      room:loseHp(player, 1, self.name)
    end
    room:damage{
      from = player,
      to = target,
      damage = 1,
      skillName = self.name,
    }
  end,
}
Fk:addSkill(hs__qiangxi)

local quhu = fk.CreateActiveSkill{
  name = "quhu__xizhicai",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and Self:canPindian(target) and target.hp > Self.hp
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local pindian = player:pindian({target}, self.name)
    if pindian.results[target.id].winner == player then
      local targets = {}
      for _, p in ipairs(room:getOtherPlayers(target)) do
        if target:inMyAttackRange(p) then
          table.insert(targets, p.id)
        end
      end
      if #targets == 0 then return end
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#quhu-choose", self.name)
      room:damage{
        from = target,
        to = room:getPlayerById(tos[1]),
        damage = 1,
        skillName = self.name,
      }
    else
      room:damage{
        from = target,
        to = player,
        damage = 1,
        skillName = self.name,
      }
    end
  end,
}
local jieming = fk.CreateTriggerSkill{
  name = "hs__jieming__xizhicai",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local to = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#jieming-choose", self.name, true)
    if #to > 0 then
      self.cost_data = {tos = to}
      return true
    end
    self.cancel_cost = true
  end,
  on_use = function(self, event, target, player, data)
    local to = player.room:getPlayerById(self.cost_data.tos[1])
    local num = math.min(to.maxHp, 5) - to:getHandcardNum()
    if num > 0 then
      to:drawCards(num, self.name)
    end
  end,
}

Fk:addSkill(quhu)
Fk:addSkill(jieming)

local xingshang = fk.CreateTriggerSkill{
  name = "xingshang__xizhicai",
  anim_type = "drawcard",
  events = {fk.Death},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and not target:isNude()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards_id = target:getCardIds{Player.Hand, Player.Equip}
    room:obtainCard(player.id, cards_id, false, fk.ReasonPrey)
  end,
}
local fangzhu = fk.CreateTriggerSkill{
  name = "hs__fangzhu__xizhicai",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1, "#hs__fangzhu-choose:::"..player:getLostHp(), self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local num = player:getLostHp()
    if to.hp > 0 and #room:askForDiscard(to, num, num, true, self.name, true, nil, "hs__fangzhu_ask:::" .. num, false) > 0 then
      if not to.dead then room:loseHp(to, 1, self.name) end
    else
      to:drawCards(num, self.name)
      if not to.dead then to:turnOver() end
    end
  end,
}
Fk:addSkill(xingshang)
Fk:addSkill(fangzhu)

local xiaoguo = fk.CreateTriggerSkill{
  name = "hs__xiaoguo__xizhicai",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target ~= player and player:hasSkill(self) and target.phase == Player.Finish and not player:isKongcheng()
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForDiscard(player, 1, 1, true, self.name, true, ".|.|.|.|.|basic", "#hs__xiaoguo-invoke::"..target.id, true)
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data, self.name, player, player)
    if #room:askForDiscard(target, 1, 1, true, self.name, true, ".|.|.|.|.|equip", "#hs__xiaoguo-discard:"..player.id) == 0 then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    elseif not player.dead then
      player:drawCards(1, self.name)
    end
  end,
}
Fk:addSkill(xiaoguo)

-- 阵势变权
local tuntian = fk.CreateTriggerSkill{
  name = "ld__tuntian__xizhicai",
  anim_type = "special",
  derived_piles = "ld__dengai_field",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player.phase == Player.NotActive then
      for _, move in ipairs(data) do
        if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".|.|spade,club,diamond",
    }
    room:judge(judge)
    if judge.card.suit ~= Card.Heart and room:getCardArea(judge.card.id) == Card.DiscardPile and
      room:askForSkillInvoke(player, self.name, nil, "ld__tuntian_field:::" .. judge.card:toLogString()) then
      player:addToPile("ld__dengai_field", judge.card, true, self.name)
    end
  end,
}

local tuntian_distance = fk.CreateDistanceSkill{
  name = "#ld__tuntian_distance__xizhicai",
  correct_func = function(self, from, to)
    if from:hasSkill(self) then
      return -#from:getPile("ld__dengai_field")
    end
  end,
}
tuntian:addRelatedSkill(tuntian_distance)
Fk:addSkill(tuntian)

local hengjiang = fk.CreateTriggerSkill{
  name = "hengjiang__xizhicai",
  anim_type = "masochism",
  events = { fk.Damaged },
  can_trigger = function(self, _, target, player, _)
    if target ~= player or not player:hasSkill(self) then return false end
    local current = player.room.current
    return current ~= nil and not current.dead
  end,
  on_use = function(_, _, _, player, data)
    local room = player.room
    local target = room.current
    if target ~= nil and not target.dead then
      room:doIndicate(player.id, {target.id})
      room:addPlayerMark(target, "@hengjiang-turn", math.max(1, #target:getCardIds("e")))
      room:addPlayerMark(target, MarkEnum.MinusMaxCardsInTurn, math.max(1, #target:getCardIds("e")))
    end
  end
}
local hengjiangdelay = fk.CreateTriggerSkill{
  name = "#hengjiang_delay__xizhicai",
  anim_type = "drawcard",
  events = { fk.TurnEnd },
  --FIXME:如何体现这个技能是延迟效果？
  can_trigger = function(_, _, target, player, _)
    if player.dead or player:usedSkillTimes(hengjiang.name) == 0 then return false end
    local room = player.room
    local discard_ids = {}
    room.logic:getEventsOfScope(GameEvent.Phase, 1, function (e)
      if e.data[2] == Player.Discard then
        table.insert(discard_ids, {e.id, e.end_id})
      end
      return false
    end, Player.HistoryTurn)
    if #discard_ids > 0 then
      if #room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
        local in_discard = false
        for _, ids in ipairs(discard_ids) do
          if #ids == 2 and e.id > ids[1] and e.id < ids[2] then
            in_discard = true
            break
          end
        end
        if in_discard then
          for _, move in ipairs(e.data) do
            if move.from == target.id and move.moveReason == fk.ReasonDiscard then
              for _, info in ipairs(move.moveInfo) do
                if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                  return true
                end
              end
            end
          end
        end
        return false
      end, Player.HistoryTurn) > 0 then
        return false
      end
    end
    return true
  end,
  on_cost = Util.TrueFunc,
  on_use = function(_, _, _, player, _)
    if player:getHandcardNum() < player.maxHp then
      player:drawCards(player.maxHp - player:getHandcardNum() , hengjiang.name)
    end
  end,
}
hengjiang:addRelatedSkill(hengjiangdelay)
Fk:addSkill(hengjiang)

local xunxun = fk.CreateTriggerSkill{
  name = "xunxun__xizhicai",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local ret = room:askForArrangeCards(player, self.name, {room:getNCards(4), "Bottom", "Top"}, "#xunxun", true, 0, {4, 2}, {0, 2})
    local top, bottom = ret[2], ret[1]
    for i = #top, 1, -1 do
      table.insert(room.draw_pile, 1, top[i])
    end
    for i = 1, #bottom, 1 do
      table.insert(room.draw_pile, bottom[i])
    end
    room:sendLog{
      type = "#GuanxingResult",
      from = player.id,
      arg = #top,
      arg2 = #bottom,
    }
  end,
}
local wangxi = fk.CreateTriggerSkill{
  name = "wangxi__xizhicai",
  events = {fk.Damage, fk.Damaged},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from and data.from ~= data.to and not (data.from.dead or data.to.dead)
  end,
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    for i = 1, data.damage do
      if i > 1 and self.cancel_cost or not self:triggerable(event, target, player, data) then break end
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local to = event == fk.Damage and data.to or data.from
    local room = player.room
    if room:askForSkillInvoke(player, self.name, nil, "#wangxi-invoke::"..to.id) then
      room:doIndicate(player.id, {to.id})
      return true
    end
    self.cancel_cost = true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    room:notifySkillInvoked(player, self.name, event == fk.Damaged and "masochism" or "drawcard")
    local tos = {player.id}
    table.insertIfNeed(tos, data.from.id)
    table.insertIfNeed(tos, data.to.id)
    room:sortPlayersByAction(tos)
    for _, pid in ipairs(tos) do
      local to = room:getPlayerById(pid)
      if not to.dead then
        room:drawCards(to, 1, self.name)
      end
    end
  end
}
Fk:addSkill(xunxun)
Fk:addSkill(wangxi)

local ld__qice = fk.CreateActiveSkill{
  name = "ld__qice__xizhicai",
  prompt = "#ld__qice-active",
  interaction = function()
    local handcards = Self:getCardIds(Player.Hand)
    local names, all_names = {} , {}
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if card:isCommonTrick() and not card.is_derived and not table.contains(all_names, card.name) then
        table.insert(all_names, card.name)
        local to_use = Fk:cloneCard(card.name)
        to_use:addSubcards(handcards)
        if Self:canUse(to_use) and not Self:prohibitUse(to_use) then
          local x = 0
          if to_use.multiple_targets and to_use.skill:getMinTargetNum() == 0 then
            for _, p in ipairs(Fk:currentRoom().alive_players) do
              if not Self:isProhibited(p, card) and card.skill:modTargetFilter(p.id, {}, Self.id, card, true) then
                x = x + 1
              end
            end
          end
          if x <= Self:getHandcardNum() then
            table.insert(names, card.name)
          end
        end
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names, all_choices = all_names}
  end,
  card_num = 0,
  min_target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    if self.interaction.data == nil then return false end
    local to_use = Fk:cloneCard(self.interaction.data)
    to_use.skillName = self.name
    to_use:addSubcards(Self:getCardIds(Player.Hand))
    if not to_use.skill:targetFilter(to_select, selected, selected_cards, to_use) then return false end
    if (#selected == 0 or to_use.multiple_targets) and
    Self:isProhibited(Fk:currentRoom():getPlayerById(to_select), to_use) then return false end
    if to_use.multiple_targets then
      if #selected >= Self:getHandcardNum() then return false end
      if to_use.skill:getMaxTargetNum(Self, to_use) == 1 then
        local x = 0
        for _, p in ipairs(Fk:currentRoom().alive_players) do
          if p.id == to_select or (not Self:isProhibited(p, to_use) and to_use.skill:modTargetFilter(p.id, {to_select}, Self.id, to_use, true)) then
            x = x + 1
          end
        end
        if x > Self:getHandcardNum() then return false end
      end
    end
    return true
  end,
  feasible = function(self, selected, selected_cards)
    if self.interaction.data == nil then return false end
    local to_use = Fk:cloneCard(self.interaction.data)
    to_use.skillName = self.name
    to_use:addSubcards(Self:getCardIds(Player.Hand))
    return to_use.skill:feasible(selected, selected_cards, Self, to_use)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local use = {
      from = player.id,
      tos = table.map(effect.tos, function (id)
        return {id}
      end),
      card = Fk:cloneCard(self.interaction.data),
    }
    use.card:addSubcards(player:getCardIds(Player.Hand))
    use.card.skillName = self.name
    room:useCard(use)
    if not player.dead and player:getMark("@@ld__qice_transform__xizhicai") == 0 and room:askForChoice(player, {"transform_deputy", "Cancel"}, self.name) ~= "Cancel" then
      room:setPlayerMark(player, "@@ld__qice_transform__xizhicai", 1)
      H.transformGeneral(room, player)
    end
  end,
}

local zhiyu = fk.CreateTriggerSkill{
  name = "ld__zhiyu__xizhicai",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:drawCards(1, self.name)
    local cards = player:getCardIds("h")
    player:showCards(cards)
    if data.from and not data.from.dead and not data.from:isKongcheng() and
      table.every(cards, function(id) return #cards == 0 or Fk:getCardById(id).color == Fk:getCardById(cards[1]).color end) then
      room:askForDiscard(data.from, 1, 1, false, self.name, false)
    end
  end,
}

Fk:addSkill(ld__qice)
Fk:addSkill(zhiyu)

local wanwei = fk.CreateTriggerSkill{
  name = "ld__wanwei__xizhicai",
  events = {fk.BeforeCardsMove},
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    local _data = {}
    for index, move in ipairs(data) do
      local num = 0
      if (move.moveReason == fk.ReasonPrey or move.moveReason == fk.ReasonDiscard) and move.from == player.id and move.proposer ~= player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip or info.fromArea == Card.PlayerHand then
            num = num + 1
          end
        end
      end
      if num ~= 0 then
        table.insert(_data, {index, num})
      end
    end
    if #_data == 0 then return end
    self.cost_data = _data
    return true
  end,
  on_use = function(self, event, target, player, data)
    if player.dead then return end
    local room = player.room
    local _data = self.cost_data
    for _, tab in ipairs(_data) do
      local index, num = tab[1], tab[2]
      local ids = room:askForCardsChosen(player, player, num, num, "he", self.name, "#ld__wanwei-choose")
      if #ids == num then
        local moveInfo = {}
        for _, id in ipairs(ids) do
          local from = room:getCardArea(id)
          local info = {}
          info.cardId = id
          info.fromArea = from
          table.insertIfNeed(moveInfo, info)
        end
        if #moveInfo == num then
          data[index].moveInfo = moveInfo
        end
      end
    end
  end,
}

Fk:addSkill(wanwei)

local jieyue = fk.CreateTriggerSkill{
  name = "ld__jieyue__xizhicai",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start and not player:isKongcheng() and table.find(player.room.alive_players, function(p) return
      p.kingdom ~= "wei"
    end)
  end,
  on_cost = function(self, event, target, player, data)
    local plist, cid = player.room:askForChooseCardAndPlayers(player, table.map(table.filter(player.room.alive_players, function(p) return
      p.kingdom ~= "wei" and p ~= player
    end), Util.IdMapper), 1, 1, ".|.|.|hand", "#ld__jieyue-target", self.name, true)
    if #plist > 0 then
      self.cost_data = {plist[1], cid}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = self.cost_data[1]
    local target = room:getPlayerById(to)
    room:moveCardTo(self.cost_data[2], Player.Hand, target, fk.ReasonGive, self.name, nil, false, player.id)
    if H.askCommandTo(player, target, self.name) then
      player:drawCards(1, self.name)
    else
      room:addPlayerMark(player, "_ld__jieyue__xizhicai-turn")
    end
  end
}
local jieyue_draw = fk.CreateTriggerSkill{
  name = "#ld__jieyue_draw__xizhicai",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.DrawNCards},
  can_use = function(self, event, target, player, data)
    return target == player and target:getMark("_ld__jieyue__xizhicai-turn") > 0
  end,
  on_use = function(self, event, target, player, data)
    data.n = data.n + 3 * target:getMark("_ld__jieyue__xizhicai-turn")
  end,
}

jieyue:addRelatedSkill(jieyue_draw)
Fk:addSkill(jieyue)

local zhengbi = fk.CreateTriggerSkill{
  name = "ld__zhengbi__xizhicai",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
      and (table.find(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id).type == Card.TypeBasic end) or table.every(player.room:getOtherPlayers(player), function(p) return H.getGeneralsRevealedNum(p) == 0 end))
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choices = {}
    local basic_cards1 = table.filter(player:getCardIds(Player.Hand), function(id)
      return Fk:getCardById(id).type == Card.TypeBasic end)
    local targets1 = table.map(table.filter(room:getOtherPlayers(player), function(p)
      return H.getGeneralsRevealedNum(p) > 0 end), Util.IdMapper)
    local targets2 = table.map(table.filter(room:getOtherPlayers(player), function(p)
      return H.getGeneralsRevealedNum(p) == 0 end), Util.IdMapper)
    if #basic_cards1 > 0 and #targets1 > 0 then
      table.insert(choices, "zhengbi_giveCard")
    end
    if #targets2 > 0 then
      table.insert(choices, "zhengbi_useCard")
    end
    if #choices == 0 then return false end
    local choice = room:askForChoice(player, choices, self.name)
    if choice:startsWith("zhengbi_giveCard") then
      local tos, id = room:askForChooseCardAndPlayers(player, targets1, 1, 1, ".|.|.|.|.|basic", "#ld__zhengbi-give", self.name, true)
      room:obtainCard(tos[1], id, false, fk.ReasonGive)
      local to = room:getPlayerById(tos[1])
      if to.dead or to:isNude() then return end
      local cards2 = to:getCardIds("he")
      if #cards2 > 1 then
        local card_choices = {}
        local num = #table.filter(to:getCardIds(Player.Hand), function(id)
          return Fk:getCardById(id).type == Card.TypeBasic end)
        if num > 1 then
          table.insert(card_choices, "zhengbi__basic-back:"..player.id)
        end
        if #to:getCardIds("he") - num > 0 then
          table.insert(card_choices, "zhengbi__nobasic-back:"..player.id)
        end
        if #card_choices == 0 then return false end
        local card_choice = room:askForChoice(to, card_choices, self.name)
        if card_choice:startsWith("zhengbi__basic-back") then
          cards2 = room:askForCard(to, 2, 2, false, self.name, false, ".|.|.|.|.|basic", "#ld__zhengbi-give1:"..player.id)
        elseif card_choice:startsWith("zhengbi__nobasic-back") then
          cards2 = room:askForCard(to, 1, 1, true, self.name, false, ".|.|.|.|.|^basic", "#ld__zhengbi-give2:"..player.id)
        end
      end
      room:moveCardTo(cards2, Player.Hand, player, fk.ReasonGive, self.name, nil, false, player.id)
    elseif choice:startsWith("zhengbi_useCard") then
      local to = room:askForChoosePlayers(player, targets2, 1, 1, "#ld__zhengbi_choose", self.name, true)
      if #to then
        room:setPlayerMark(room:getPlayerById(to[1]), "@@ld__zhengbi_choose-turn", 1)
      end
    end
  end,

  refresh_events = {fk.GeneralRevealed},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self) and target:getMark("@@ld__zhengbi_choose-turn") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(target, "@@ld__zhengbi_choose-turn", 0)
  end,
}

local zhengbi_targetmod = fk.CreateTargetModSkill{
  name = "#ld__zhengbi_targetmod__xizhicai",
  frequency = Skill.Compulsory,
  bypass_times = function(self, player, skill, scope, card, to)
    return player:hasSkill(zhengbi) and to:getMark("@@ld__zhengbi_choose-turn") > 0
  end,
  bypass_distances =  function(self, player, skill, card, to)
    return player:hasSkill(zhengbi) and to:getMark("@@ld__zhengbi_choose-turn") > 0
  end,
}
zhengbi:addRelatedSkill(zhengbi_targetmod)
Fk:addSkill(zhengbi)


local huibian = fk.CreateActiveSkill{
  name = "huibian__xizhicai",
  anim_type = "control",
  target_num = 2,
  card_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    if #selected == 0 then
      local target2 = Fk:currentRoom():getPlayerById(to_select)
      return target2.kingdom == "wei"
    elseif #selected == 1 then
      local target1 = Fk:currentRoom():getPlayerById(to_select)
      return target1.kingdom == "wei" and target1:isWounded()
    else
      return false
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target1 = room:getPlayerById(effect.tos[1])
    local target2 = room:getPlayerById(effect.tos[2])
    room:damage{
      from = player,
      to = target1,
      damage = 1,
      skillName = self.name,
    }
    if not target1.dead then
      target1:drawCards(2, self.name)
    end
    if not target2.dead and target2:isWounded() then
      room:recover{
        who = target2,
        num = 1,
        recoverBy = player,
        skillName = self.name
      }
    end
  end,
}

Fk:addSkill(huibian)


-- 不臣篇
local quanjin = fk.CreateActiveSkill{
  name = "quanjin__xizhicai",
  prompt = "#quanjin-active",
  anim_type = "control",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_num = 1,
  card_filter = function(self, to_select, selected)
    return #selected < 1 and Fk:currentRoom():getCardArea(to_select) == Player.Hand
  end,
  target_num = 1,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= Self.id and Fk:currentRoom():getPlayerById(to_select):getMark("_quanjin-phase") > 0 -- and #selected_cards == 1
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:moveCardTo(effect.cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, false, player.id)
    if H.askCommandTo(player, target, self.name) then
      player:drawCards(1, self.name)
    else
      local num = player:getHandcardNum()
      for hc, p in ipairs(room.alive_players) do
        hc = p:getHandcardNum()
        if hc > num then
          num = hc
        end
      end
      num = math.min(num - player:getHandcardNum(), 5)
      player:drawCards(num, self.name)
    end
  end,
}
local quanjinRecorder = fk.CreateTriggerSkill{
  name = "#quanjin_recorder__xizhicai",
  visible = false,
  refresh_events = {fk.Damaged, fk.EventAcquireSkill},
  can_refresh = function(self, event, target, player, data)
    if not (player:hasSkill(quanjin) or player:isFakeSkill(quanjin)) or player.phase ~= Player.Play then return false end
    return event == fk.Damaged or (target == player and data == quanjin)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.Damaged then
      room:setPlayerMark(target, "_quanjin-phase", 1)
    elseif room:getTag("RoundCount") then
      room.logic:getActualDamageEvents(998, function(e)
        local damage = e.data[1]
        local to = damage.to
        if to and to:getMark("_quanjin-phase") == 0 then
          room:setPlayerMark(to, "_quanjin-phase", 1)
        end
        return false
      end, Player.HistoryPhase)
    end
  end,
}

local zaoyun = fk.CreateActiveSkill{
  name = "zaoyun__xizhicai",
  anim_type = "offensive",
  prompt = "#zaoyun",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and player.kingdom ~= "unknown"
  end,
  min_card_num = 1,
  card_filter = function(self, to_select, selected)
    return Fk:currentRoom():getCardArea(to_select) == Player.Hand and not Self:prohibitDiscard(Fk:getCardById(to_select))
  end,
  target_num = 1,
  target_filter = function(self, to_select, selected, selected_cards)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and H.compareKingdomWith(target, Self, true)
      and Self:distanceTo(target) - 1 == #selected_cards and #selected_cards > 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    room:setPlayerMark(player, "_zaoyun_distance-turn", target.id)
    room:damage{ from = player, to = target, damage = 1, skillName = self.name }
  end,
}
local zaoyun_distance = fk.CreateDistanceSkill{
  name = "#zaoyun_distance__xizhicai",
  fixed_func = function(self, from, to)
    if from:getMark("_zaoyun_distance-turn") == to.id then
      return 1
    end
  end,
}

quanjin:addRelatedSkill(quanjinRecorder)
zaoyun:addRelatedSkill(zaoyun_distance)
Fk:addSkill(quanjin)
Fk:addSkill(zaoyun)

local juejue = fk.CreateTriggerSkill{
  name = "ld__juejue__xizhicai",
  anim_type = "offensive",
  events = {fk.EventPhaseStart, fk.BuryVictim},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    if event == fk.EventPhaseStart then
      return target == player and player.phase == Player.Discard
    else
      return data.damage and data.damage.from == player and H.compareKingdomWith(player, target)
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return player.room:askForSkillInvoke(player, self.name, data, "#ld__juejue-ask")
    else
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      room:loseHp(player, 1, self.name)
    else
      local deathEvent = room.logic:getCurrentEvent():findParent(GameEvent.Death, true).data[1]
      deathEvent.extra_data = deathEvent.extra_data or {}
      deathEvent.extra_data.ignorePunishment = true
    end
  end,
}

local juejue_delay = fk.CreateTriggerSkill{
  name = "#ld__juejue_delay__xizhicai",
  events = {fk.EventPhaseEnd},
  can_trigger = function (self, event, target, player, data)
    if not (target == player and player.phase == Player.Discard and player:isAlive() and player:usedSkillTimes(juejue.name, Player.HistoryPhase) > 0) then return false end
    local x = 0
    local logic = player.room.logic
    logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
      for _, move in ipairs(e.data) do
        if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.skillName == "phase_discard" then
          x = x + #move.moveInfo
          if x > 1 then return true end
        end
      end
      return false
    end, Player.HistoryTurn)
    self.cost_data = x
    return x > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local targets = room:getOtherPlayers(player)
    local n = self.cost_data
    for _, target in ipairs(targets) do
      if not target.dead then
        local choices = {"ld__juejue_damage"}
        if #target:getCardIds("h") >= n then
          table.insert(choices, "ld__juejue_putcard")
        end
        local choice = room:askForChoice(target, choices, self.name)
        if choice == "ld__juejue_damage" then
          room:damage{
            from = player,
            to = target,
            damage = 1,
            skillName = self.name,
          }
        else
          local card = room:askForCard(target, n, n, true, self.name, false, ".|.|.|hand", nil)
          room:moveCardTo(card, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name)
        end
      end
    end
  end,
}

juejue:addRelatedSkill(juejue_delay)
Fk:addSkill(juejue)

local qiuan = fk.CreateTriggerSkill{
  name = "ld__qiuan__xizhicai",
  anim_type = "masochism",
  events = {fk.DamageInflicted},
  derived_piles = "ld__mengda_letter",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and data.card
      and #player:getPile("ld__mengda_letter") == 0 and U.hasFullRealCard(player.room, data.card)
  end,
  on_use = function(self, event, target, player, data)
    player:addToPile("ld__mengda_letter", data.card, true, self.name)
    if #player:getPile("ld__mengda_letter") > 0 then
      return true
    end
  end,
}

Fk:addSkill(qiuan)

local bushi = fk.CreateTriggerSkill{
  name = "ld__bushi__xizhicai",
  anim_type = "defensive",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Finish
      and player:getMark("ld__bushi-turn") > 0 and #player:getPile("ld__midao_rice") > 0
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForCard(player, 1, 1, false, self.name, true, ".|.|.|ld__midao_rice", "#ld__bushi_discard", "ld__midao_rice")
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:moveCardTo(self.cost_data, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, "ld__midao_rice", true, player.id)
    local targets = table.map(room.alive_players, Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, player.maxHp, "#ld__midao-choose", self.name, false)
    room:sortPlayersByAction(tos)
    if #tos == 0 then
      tos = table.random(targets, 1)
    end
    for _, id in ipairs(tos) do
      local p = room:getPlayerById(id)
      if not p.dead then
        p:drawCards(1, self.name)
      end
    end
    for _, id in ipairs(tos) do
      local p = room:getPlayerById(id)
      if not p.dead then
        local card = room:askForCard(p, 1, 1, true, self.name, true, nil, "#ld__bushi")
        if #card > 0 then
          player:addToPile("ld__midao_rice", card, true, self.name)
        end
      end
    end
  end,

  refresh_events = {fk.Damage, fk.Damaged},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:addPlayerMark(player, "ld__bushi-turn", 1)
  end,
}

local midao = fk.CreateTriggerSkill{
  name = "ld__midao__xizhicai",
  anim_type = "offensive",
  derived_piles = "ld__midao_rice",
  events = {fk.GeneralRevealed, fk.AskForRetrial},
  can_trigger = function (self, event, target, player, data)
    if event == fk.GeneralRevealed then
      if player:hasSkill(self) then
        for _, v in pairs(data) do
          if table.contains(Fk.generals[v]:getSkillNameList(), self.name) then return true end
        end
      end
    elseif event == fk.AskForRetrial then
      return player:hasSkill(self) and #player:getPile("ld__midao_rice") > 0
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.GeneralRevealed then
      return true
    elseif event == fk.AskForRetrial then
      local card = player.room:askForCard(player, 1, 1, false, self.name, true, ".|.|.|ld__midao_rice", "#ld__midao-ask::" .. target.id .. ":" .. data.reason, "ld__midao_rice")
      if #card > 0 then
        self.cost_data = card[1]
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    if event == fk.GeneralRevealed then
      player:drawCards(2, self.name)
      if player:isNude() then return end
      local cards
      if #player:getCardIds("he") < 3 then
        cards = player:getCardIds("he")
      else
        cards = player.room:askForCard(player, 2, 2, true, self.name, false, ".", "#ld__midao")
      end
      player:addToPile("ld__midao_rice", cards, true, self.name)
    elseif event == fk.AskForRetrial then
      player.room:retrial(Fk:getCardById(self.cost_data), player, data, self.name, true)
    end
  end,
}

Fk:addSkill(bushi)
Fk:addSkill(midao)

local jinfa = fk.CreateActiveSkill{
  name = "ld__jinfa__xizhicai",
  anim_type = "offensive",
  card_num = 1,
  target_num = 1,
  can_use = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isNude()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and not Self:prohibitDiscard(to_select)
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and not target:isNude() and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    local card1 = room:askForCard(target, 1, 1, true, self.name, true, ".|.|.|.|.|equip", "ld__jinfa_give")
    if #card1 == 1 then
      room:obtainCard(player.id, card1[1], true, fk.ReasonGive)
      if Fk:getCardById(card1[1]).suit == Card.Spade then
        local card = Fk:cloneCard("slash")
        if not (target:prohibitUse(card) or target:isProhibited(player, card)) then
          room:useVirtualCard("slash", nil, target, player)
        end
      end
    else
      local card2 = room:askForCardChosen(player, target, "he", self.name)
      room:obtainCard(player, card2, false, fk.ReasonPrey)
    end
  end,
}

Fk:addSkill(jinfa)

local chenglue = fk.CreateTriggerSkill{
  name = "ld__chenglue__xizhicai",
  anim_type = "drawcard",
  events = {fk.TargetSpecified},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and H.compareKingdomWith(target, player) and #AimGroup:getAllTargets(data.tos) > 1 and data.firstTarget
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#ld__chenglue-ask:" .. target.id)
  end,
  on_use = function(self, event, target, player, data)
    if target:isAlive() then
      target:drawCards(1, self.name)
    end
    data.extra_data = data.extra_data or {}
    data.extra_data.ld__chenglueUser = data.extra_data.ld__chenglueUser or {}
    data.extra_data.ld__chenglueUser[player.id] = true
  end,
}
local chenglue_after = fk.CreateTriggerSkill{
  name = "#ld__chenglue_after__xizhicai",
  events = {fk.CardUseFinished},
  mute = true,
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    return ((data.extra_data or {}).ld__chenglueUser or {})[player.id]
      and data.damageDealt and data.damageDealt[player.id]
  end,
  on_cost = function(self, event, target, player, data)
    local targets = table.map(table.filter(player.room.alive_players, function(p)
      return H.compareKingdomWith(p, player)
        and p:getMark("@!yinyangfish") == 0 and p:getMark("@!companion") == 0
        and p:getMark("@!wild") == 0 and p:getMark("@!vanguard") == 0
    end), Util.IdMapper)
    if #targets == 0 then return end
    local to = player.room:askForChoosePlayers(player, targets, 1, 1, "#ld__chenglue-give", self.name, true)
    if #to == 1 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    H.addHegMark(player.room, player.room:getPlayerById(self.cost_data), "yinyangfish")
  end,
}
chenglue:addRelatedSkill(chenglue_after)
Fk:addSkill(chenglue)

-- 十周年
local wanggui = fk.CreateTriggerSkill{
  name = "ty_heg__wanggui__xizhicai",
  mute = true,
  events = {fk.Damage, fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasShownSkill(self) and player:usedSkillTimes(self.name) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if player.general ~= "anjiang" and player.deputyGeneral ~= "anjiang" then
      if room:askForSkillInvoke(player, self.name, data, "#ty_heg__wanggui_draw-invoke") then
        self.cost_data = nil
        return true
      end
    else
      local targets = table.map(table.filter(room.alive_players, function(p)
        return H.compareKingdomWith(p, player, true) end), Util.IdMapper)
      if #targets == 0 then return end
      local to = room:askForChoosePlayers(player, targets, 1, 1, "#ty_heg__wanggui_damage-choose", self.name, true)
      if #to > 0 then
        self.cost_data = to[1]
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if self.cost_data then
      room:notifySkillInvoked(player, self.name, "offensive")
      local to = room:getPlayerById(self.cost_data)
      room:damage{
        from = player,
        to = to,
        damage = 1,
        skillName = self.name,
      }
    else
      room:notifySkillInvoked(player, self.name, "drawcard")
      local targets = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) end), Util.IdMapper)
      room:sortPlayersByAction(targets)
      for _, pid in ipairs(targets) do
        local p = room:getPlayerById(pid)
        if not p.dead then
          p:drawCards(1, self.name)
        end
      end
    end
  end,
}
local xibing = fk.CreateTriggerSkill{
  name = "ty_heg__xibing__xizhicai",
  anim_type = "control",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and target ~= player and target.phase == Player.Play and
      data.card.color == Card.Black and (data.card.trueName == "slash" or data.card:isCommonTrick()) and #AimGroup:getAllTargets(data.tos) == 1) then return false end
    local events = target.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e) 
      local use = e.data[1]
      return use.from == target.id and use.card.color == Card.Black and (use.card.trueName == "slash" or use.card:isCommonTrick())
    end, Player.HistoryTurn)
    return #events == 1 and events[1].id == target.room.logic:getCurrentEvent().id
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#ty_heg__xibing-invoke::"..target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, {target.id})
    local num = math.min(target.hp, 5) - target:getHandcardNum()
    local cards
    if num > 0 then
      cards = target:drawCards(num, self.name)
    end
    if H.getGeneralsRevealedNum(player) == 2 and H.getGeneralsRevealedNum(target) == 2
      and room:askForChoice(player, {"ty_heg__xibing_hide::" .. target.id, "Cancel"}, self.name) ~= "Cancel" then
      for _, p in ipairs({player, target}) do
        local isDeputy = H.doHideGeneral(room, player, p, self.name)
        room:setPlayerMark(p, "@ty_heg__xibing_reveal-turn", H.getActualGeneral(p, isDeputy))
        local record = type(p:getMark(MarkEnum.RevealProhibited .. "-turn")) == "table" and p:getMark(MarkEnum.RevealProhibited .. "-turn") or {}
        table.insert(record, isDeputy and "d" or "m")
        room:setPlayerMark(p, MarkEnum.RevealProhibited .. "-turn", record)
      end
    end
    if cards and not target.dead then
      room:setPlayerMark(target, "@@ty_heg__xibing-turn", 1)
    end
  end,
}
local xibing_prohibit = fk.CreateProhibitSkill{
  name = "#ty_heg__xibing_prohibit__xizhicai",
  prohibit_use = function(self, player, card)
    if player:getMark("@@ty_heg__xibing-turn") == 0 then return false end 
    local subcards = Card:getIdList(card)
    return #subcards > 0 and table.every(subcards, function(id)
      return table.contains(player:getCardIds(Player.Hand), id)
    end)
  end,
}
xibing:addRelatedSkill(xibing_prohibit)
Fk:addSkill(wanggui)
Fk:addSkill(xibing)

local deshao = fk.CreateTriggerSkill{
  name = "ty_heg__deshao__xizhicai",
  anim_type = "defensive",
  events = {fk.TargetSpecified},
  can_trigger = function (self, event, target, player, data)
    return target ~= player and player:hasSkill(self) and U.isOnlyTarget(player, data, event)
      and data.card.color == Card.Black and H.getGeneralsRevealedNum(player) >= H.getGeneralsRevealedNum(target) 
      and player:usedSkillTimes(self.name, Player.HistoryTurn) < player.hp
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#ty_heg__deshao-invoke::"..data.from)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local from = room:getPlayerById(data.from)
    if not from:isNude() then
      local id = room:askForCardChosen(player, from, "he", self.name)
      room:throwCard(id, self.name, from, player)
    end
  end,
}

local mingfa = fk.CreateActiveSkill{
  name = "ty_heg__mingfa__xizhicai",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  can_use = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function (self, to_select, selected)
    return false
  end,
  target_filter = function (self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and (not H.compareKingdomWith(Fk:currentRoom():getPlayerById(to_select), Self))
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    local mark = type(target:getMark("@@ty_heg__mingfa_delay__xizhicai")) == "table" and target:getMark("@@ty_heg__mingfa_delay__xizhicai") or {}
    table.insert(mark, effect.from)
    room:setPlayerMark(target, "@@ty_heg__mingfa_delay__xizhicai", mark)
  end,
}

local mingfa_delay = fk.CreateTriggerSkill{
  name = "#ty_heg__mingfa_delay__xizhicai",
  anim_type = "offensive",
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    if target.dead or player.dead then return false end
    return table.contains(target:getTableMark("@@ty_heg__mingfa_delay__xizhicai"), player.id)
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if player:getHandcardNum() > target:getHandcardNum() then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
      if target:getHandcardNum() > 0 then
        local cards = room:askForCardsChosen(player, target, 1, 1, "h", self.name)
        room:obtainCard(player, cards, false, fk.ReasonPrey)
      end
    elseif player:getHandcardNum() < target:getHandcardNum() then
      player:drawCards(math.min(target:getHandcardNum() - player:getHandcardNum(), 5), self.name)
    end
  end,

  refresh_events = {fk.AfterTurnEnd, fk.BuryVictim},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterTurnEnd then
      return player == target and player:getMark("@@ty_heg__mingfa_delay__xizhicai") ~= 0
    elseif event == fk.BuryVictim then
      local mark = player:getMark("@@ty_heg__mingfa_delay__xizhicai")
      return type(mark) == "table" and table.every(player.room.alive_players, function (p)
        return not table.contains(mark, p.id)
      end)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "@@ty_heg__mingfa_delay__xizhicai", 0)
  end,
}

mingfa:addRelatedSkill(mingfa_delay)
Fk:addSkill(deshao)
Fk:addSkill(mingfa)

local weicheng = fk.CreateTriggerSkill{
  name = "ty_heg__weicheng__xizhicai",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or player:getHandcardNum() >= player.hp then return false end
    for _, move in ipairs(data) do
      if move.from and move.from == player.id and move.to and move.to ~= player.id and move.toArea == Card.PlayerHand then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand then
            return true
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}
local daoshu = fk.CreateActiveSkill{
  name = "ty_heg__daoshu__xizhicai",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local suits = {"log_spade", "log_club", "log_heart", "log_diamond"}
    local choice = room:askForChoice(player, suits, self.name)
    room:sendLog{
      type = "#DaoshuLog",
      from = player.id,
      to = effect.tos,
      arg = choice,
      arg2 = self.name,
      toast = true,
    }
    local card = room:askForCardChosen(player, target, "h", self.name)
    room:obtainCard(player, card, true, fk.ReasonPrey)
    if Fk:getCardById(card):getSuitString(true) == choice then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
      player:addSkillUseHistory(self.name, -1)
    else
      local suit = Fk:getCardById(card):getSuitString(true)
      table.removeOne(suits, suit)
      suits = table.map(suits, function(s) return s:sub(5) end)
      local others = table.filter(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id):getSuitString(true) ~= suit end)
      if #others > 0 then
        local cards = room:askForCard(player, 1, 1, false, self.name, false, ".|.|"..table.concat(suits, ","),
          "#daoshu-give::"..target.id..":"..suit)
        if #cards > 0 then
          cards = cards[1]
        else
          cards = table.random(others)
        end
        room:obtainCard(target, cards, true, fk.ReasonGive)
      else
        player:showCards(player:getCardIds(Player.Hand))
      end
    end
  end,
}
Fk:addSkill(weicheng)
Fk:addSkill(daoshu)

local jianguo = fk.CreateActiveSkill{
  name = "ty_heg__jianguo__xizhicai",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#jianguo",
  interaction = function(self)
    return UI.ComboBox { choices = {"jianguo1", "jianguo2"} }
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    if self.interaction.data == "jianguo1" then
      return #selected == 0
    elseif self.interaction.data == "jianguo2" then
      return #selected == 0 and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
    end
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    if self.interaction.data == "jianguo1" then
      target:drawCards(1, self.name)
      if not target.dead and target:getHandcardNum() > 1 then
        local n = target:getHandcardNum() // 2
        room:askForDiscard(target, math.min(5, n), math.min(5, n), false, self.name, false)
      end
    else
      room:askForDiscard(target, 1, 1, true, self.name, false)
      if not target.dead and target:getHandcardNum() > 1 then
        local n = target:getHandcardNum() // 2
        target:drawCards(math.min(5, n), self.name)
      end
    end
  end,
}
local qingshid = fk.CreateTriggerSkill{
  name = "ty_heg__qingshid__xizhicai",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e) 
      local use = e.data[1]
      return use.from == player.id
    end, Player.HistoryTurn)
    return target == player and player:hasSkill(self) and player.phase ~= Player.NotActive and
      player:getHandcardNum() == #events and player:getHandcardNum() <= 5 and
      data.tos and data.firstTarget and table.find(AimGroup:getAllTargets(data.tos), function(id) return id ~= player.id end)
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, AimGroup:getAllTargets(data.tos), 1, 1, "#qingshid-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:damage{
      from = player,
      to = player.room:getPlayerById(self.cost_data),
      damage = 1,
      skillName = self.name,
    }
  end,
}

Fk:addSkill(jianguo)
Fk:addSkill(qingshid)

-- 海外服

local tanfeng = fk.CreateTriggerSkill{
  name = "os_heg__tanfeng__xizhicai",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      player.phase == Player.Start and table.find(player.room.alive_players, function(p) return
        not H.compareKingdomWith(p, player) and not p:isAllNude()
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local availableTargets = table.map(table.filter(room.alive_players, function(p)
        return not H.compareKingdomWith(p, player) and not p:isAllNude() -- not willBeFriendWith，救命！
      end), Util.IdMapper)
    if #availableTargets == 0 then return false end
    target = room:askForChoosePlayers(player, availableTargets, 1, 1, "#os_heg__tanfeng-ask", self.name, true)
    if #target > 0 then
      self.cost_data = target[1]
      return true
    end
    return false
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    target = room:getPlayerById(self.cost_data)
    local cid = room:askForCardChosen(player, target, "hej", self.name)
    room:throwCard({cid}, self.name, target, player)
    local choices = {"os_heg__tanfeng_damaged::" .. player.id, "Cancel"}
    local slash = Fk:cloneCard("slash")
    slash.skillName = self.name
    local choice = room:askForChoice(target, choices, self.name, nil)
    if choice ~= "Cancel" then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        damageType = fk.FireDamage,
        skillName = self.name,
      }
      if not (target.dead or player.dead) then
        local phase = {"phase_judge", "phase_draw", "phase_play", "phase_discard", "phase_finish"}
        player:skip(table.indexOf(phase, room:askForChoice(target, phase, self.name, "#os_heg__tanfeng-skip:" .. player.id)) + 2)
      end
    end
  end,
}
Fk:addSkill(tanfeng)

local danlao = fk.CreateTriggerSkill{
  name = "danlao__xizhicai",
  anim_type = "defensive",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.type == Card.TypeTrick and #AimGroup:getAllTargets(data.tos) > 1
  end,
  on_use = function(self, event, target, player, data)
    table.insertIfNeed(data.nullifiedTargets, player.id)
    player:drawCards(1, self.name)
  end,
}
local jilei = fk.CreateTriggerSkill{
  name = "jilei__xizhicai",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from and not data.from.dead
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, {"basic", "trick", "equip"}, self.name)
    local types = data.from:getMark("@jilei-turn")
    if types == 0 then types = {} end
    table.insertIfNeed(types, choice .. "_char")
    room:setPlayerMark(data.from, "@jilei-turn", types)
  end,
}
local jilei_prohibit = fk.CreateProhibitSkill{
  name = "#jilei_prohibit__xizhicai",
  prohibit_use = function(self, player, card)
    local mark = player:getMark("@jilei-turn")
    if type(mark) == "table" and table.contains(mark, card:getTypeString() .. "_char") then
      local subcards = card:isVirtual() and card.subcards or {card.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
  prohibit_response = function(self, player, card)
    local mark = player:getMark("@jilei-turn")
    if type(mark) == "table" and table.contains(mark, card:getTypeString() .. "_char") then
      local subcards = card:isVirtual() and card.subcards or {card.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
  prohibit_discard = function(self, player, card)
    local mark = player:getMark("@jilei-turn")
    return type(mark) == "table" and table.contains(mark, card:getTypeString() .. "_char")
  end,
}
jilei:addRelatedSkill(jilei_prohibit)
Fk:addSkill(danlao)
Fk:addSkill(jilei)

-- 紫星

local fuli = fk.CreateTriggerSkill{
  name = "zx_heg__fuli__xizhicai",
  anim_type = "support",
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and H.compareKingdomWith(player, target) and (player:hasShownSkill(self) or player == target)
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(target, "#zx_heg__fuli-invoke")
  end,
  on_use = function(self, event, target, player, data)
    data.n = data.n + 1
  end,
}

local fuli_delay = fk.CreateTriggerSkill{
  name = "#zx_heg__fuli_delay__xizhicai",
  events = {fk.AfterDrawNCards},
  mute = true,
  anim_type = "drawcard",
  visible = false,
  can_trigger = function(self, event, target, player, data)
    return player:usedSkillTimes("zx_heg__fuli", Player.HistoryPhase) > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card = room:askForCardChosen(target, target, "h", self.name)
    target:showCards(card)
    if target ~= player and not player.dead then
      room:obtainCard(player.id, card, false, fk.ReasonGive, player.id)
    end
    local suit = Fk:getCardById(card):getSuitString(true)
    if suit ~= "log_nosuit" then
      room:setPlayerMark(target, "@zx_heg__fuli-turn", suit)
    end
  end,
}

local fuli_prohibit = fk.CreateProhibitSkill{
  name = "#zx_heg__fuli_prohibit__xizhicai",
  prohibit_use = function(self, player, card)
    return player:getMark("@zx_heg__fuli-turn") == card:getSuitString(true)
  end,
  prohibit_response = function(self, player, card)
    return player:getMark("@zx_heg__fuli-turn") == card:getSuitString(true)
  end,
}

local fengwu = fk.CreateActiveSkill{
  name = "zx_heg__fengwu__xizhicai",
  anim_type = "control",
  card_num = 0,
  min_target_num = 1,
  max_target_num = 3,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function (self, to_select, selected)
    return not Fk:currentRoom():getPlayerById(to_select):isNude() and #selected < 3
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:sortPlayersByAction(effect.tos)
    for _, id in ipairs(effect.tos) do
      local p = room:getPlayerById(id)
      if not p.dead and not p:isNude() then
        U.askForPlayCard(room, p, nil, ".", self.name, nil, {bypass_times = true})
      end
    end
    local used_color = {}
    room.logic:getEventsByRule(GameEvent.UseCard, 1, function (e)
      local use = e.data[1]
      if use.card.suit ~= 0 then
        table.insertIfNeed(used_color, use.card.suit)
        return #used_color == 4
      end
      return false
    end, room.logic:getCurrentEvent():findParent(GameEvent.Turn, true).id)
    if #used_color == 4 then
      player:drawCards(2, self.name)
      if player.hp < player.maxHp and not player.dead then
        room:recover({
          who = player,
          num = 1,
          recoverBy = player,
          skillName = self.name
        })
      end
    end
  end
}

fuli:addRelatedSkill(fuli_prohibit)
fuli:addRelatedSkill(fuli_delay)
Fk:addSkill(fuli)
Fk:addSkill(fengwu)

local tongjun = fk.CreateTriggerSkill{
  name = "zx_heg__tongjun__xizhicai",
  anim_type = "special",
  events = {fk.EnterDying},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and H.isBigKingdomPlayer(target) and not player:isKongcheng() and not target:isKongcheng()
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local id1 = room:askForCardChosen(player, target, "h", self.name)
    local card = room:askForCard(player, 1, 1, false, self.name, true, ".", "#zx_heg__tongjun")
    if #card > 0 then
      local id2 = card[1]
      if player.dead then return end
      local move1 = {
        from = player.id,
        ids = {id2},
        to = target.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonJustMove,
        proposer = player.id,
        skillName = self.name,
      }
      local move2 = {
        from = target.id,
        ids ={id1},
        to = player.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonJustMove,
        proposer = player.id,
        skillName = self.name,
      }
    room:moveCards(move1, move2)
    end
  end,
}

Fk:addSkill(tongjun)

-- 日月
local poyuan = fk.CreateTriggerSkill{
  name = "wk_heg__poyuan__xizhicai",
  anim_type = "offensive",
  events = {fk.Damage, fk.DamageCaused},
  can_trigger = function (self, event, target, player, data)
    if not (target == player and player:hasSkill(self) and player:isAlive()) then return false end
    if event == fk.Damage then
      return data.to ~= player and not data.to.dead and #data.to:getCardIds("e") > 0
    else
      if not (H.isBigKingdomPlayer(data.to) and player.room.current == player) then return false end
      local events = player.room.logic:getActualDamageEvents(1, function(e)
        return e.data[1].from == player and H.isBigKingdomPlayer(e.data[1].to)
      end, Player.HistoryTurn)
      return #events == 0 and player:getMark("wk_heg__poyuan__xizhicai-turn") == 0
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.Damage then
      return player.room:askForSkillInvoke(player, self.name, nil, "#wk_heg__poyuan-discard")
    else
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.Damage then
      local id = room:askForCardChosen(player, data.to, "e", self.name)
      room:throwCard(id, self.name, data.to, player)
    else
      data.damage = data.damage + 1
      room:setPlayerMark(player, "wk_heg__poyuan__xizhicai-turn", 1)
    end
  end,
}

local choulue = fk.CreateTriggerSkill{
  name = "wk_heg__choulue__xizhicai",
  anim_type = "offensive",
  events = {fk.Damaged, fk.TargetSpecified},
  can_trigger = function (self, event, target, player, data)
    if event == fk.Damaged then
      return player == target and player:hasSkill(self) and player:getMark("@!yinyangfish") < player.maxHp
    else
      return player:hasSkill(self) and H.compareKingdomWith(player, target) and #AimGroup:getAllTargets(data.tos) == 1
        and data.card:isCommonTrick() and player:getMark("@!yinyangfish") ~= 0
    end
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, event == fk.Damaged and "#wk_heg__choulue-getfish" or "#wk_heg__choulue-twice")
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.Damaged then
      H.addHegMark(room, player, "yinyangfish")
    else
      room:removePlayerMark(player, "@!yinyangfish")
      if player:getMark("@!yinyangfish") == 0 then
        player:loseFakeSkill("yinyangfish_skill&")
      end
      data.additionalEffect = 1
    end
  end,
}

Fk:addSkill(poyuan)
Fk:addSkill(choulue)

local liance = fk.CreateTriggerSkill{
  name = "wk_heg__liance__xizhicai",
  anim_type = "offensive",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or not target.phase == Player.Play or player == target or player:isNude() then return false end
    local usedCardNames = {}
    return #player.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
      local use = e.data[1]
      if table.contains(usedCardNames, e.data[1].card.name) then
        return use.from == target.id and use.card:isCommonTrick()
      else
        if use.from == target.id and use.card:isCommonTrick() then
          table.insert(usedCardNames, e.data[1].card.name)
        end
        return false
      end
    end, Player.HistoryPhase) > 0
  end,
  on_cost = function(self, event, target, player, data)
    local cards = player.room:askForDiscard(player, 1, 1, true, self.name, true, ".", "#wk_heg__liance-invoke::"..target.id, true)
    if #cards == 1 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local usedCardNames = {}
    room:throwCard(self.cost_data, self.name, player, player)
    local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 998, function(e)
      local use = e.data[1]
      if table.contains(usedCardNames, e.data[1].card.name) then
        return use.from == target.id and (use.card.type == Card.TypeTrick or use.card.type == Card.TypeBasic)
      else
        if use.from == target.id and (use.card.type == Card.TypeTrick or use.card.type == Card.TypeBasic) then
          table.insert(usedCardNames, e.data[1].card.name)
        end
        return false
      end
    end, Player.HistoryPhase)
    local usedCardTwice = {}
    table.forEach(events, function(e)
      table.insertIfNeed(usedCardTwice, e.data[1].card.name)
    end)

    room:setPlayerMark(target, "wk_heg__liance-phase", usedCardTwice)
    local success, dat = player.room:askForUseActiveSkill(target, "#wk_heg__liance_viewas", "#wk_heg__liance-choose", true)
    -- if not success then
    --   H.askCommandTo(player, target, self.name, true)
    -- else
    if success then
      local card = Fk.skills["#wk_heg__liance_viewas"]:viewAs(usedCardTwice.cards)
      room:useCard{
        from = target.id,
        tos = table.map(dat.targets, function(id) return {id} end),
        card = card,
      }
    end
  end,
}

local shilun = fk.CreateTriggerSkill{
  name = "wk_heg__shilun__xizhicai",
  events = {fk.Damaged},
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    return player == target and player:hasSkill(self) and not player:isKongcheng()
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local cards = player.player_cards[Player.Hand]
    player:showCards(cards)
    local _, ret = room:askForUseActiveSkill(player, "#wk_heg__shilun_active", "#wk_heg__shilun_active-choose", false)
    local to_remain
    if ret then
      to_remain = ret.cards
    end
    local cards = table.filter(player:getCardIds{Player.Hand}, function (id)
      return not (table.contains(to_remain, id) or player:prohibitDiscard(Fk:getCardById(id)))
    end)
    if #cards > 0 then
      room:throwCard(cards, self.name, player)
    end
    local cards = player.player_cards[Player.Hand]
    if #cards == 4 then
      if #room:canMoveCardInBoard() > 0 then
        local targets = room:askForChooseToMoveCardInBoard(player, "#wk_heg__shilun-move", self.name, true, nil)
        if #targets ~= 0 then
          targets = table.map(targets, function(id) return room:getPlayerById(id) end)
          room:askForMoveCardInBoard(player, targets[1], targets[2], self.name)
        end
      end
    else
      local suits = {Card.Spade, Card.Heart, Card.Diamond, Card.Club}
      for _, id in ipairs(cards) do
        local suit = Fk:getCardById(id).suit
        if suit ~= Card.NoSuit then
          table.removeOne(suits, suit)
        end
      end
      local patternTable = { ["heart"] = {}, ["diamond"] = {}, ["spade"] = {}, ["club"] = {} }
      for _, id in ipairs(room.draw_pile) do
        local card = Fk:getCardById(id)
        if table.contains(suits, card.suit) then
          table.insert(patternTable[card:getSuitString()], id)
        end
      end
      local get = {}
      for _, ids in pairs(patternTable) do
        if #ids > 0 then
          table.insert(get, table.random(ids))
        end
      end
      if #get > 0 then
        room:obtainCard(player, get, false, fk.ReasonPrey)
      end
    end
  end,
}

Fk:addSkill(liance)
Fk:addSkill(shilun)

local dingpin = fk.CreateTriggerSkill{
  name = "wk_heg__dingpin__xizhicai",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Finish
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return p ~= player end), Util.IdMapper)
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__dingpin-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    room:setPlayerMark(to, "_wk_heg__dingpin__xizhicai", player.id)
    player:turnOver()
    to:gainAnExtraTurn(true, self.name)
  end,
}
local dingpin_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__dingpin_delay__xizhicai",
  events = {fk.EventPhaseStart, fk.TurnEnd},
  anim_type = "special",
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return target.phase == Player.Start and target:getCurrentExtraTurnReason() == "wk_heg__dingpin__xizhicai" 
       and target:getMark("_wk_heg__dingpin") == player.id and H.compareKingdomWith(player, target)
    else
      return target == player and target:getCurrentExtraTurnReason() == "wk_heg__dingpin__xizhicai"
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      room:notifySkillInvoked(player, self.name, "support")
      player:broadcastSkillInvoke(self.name)
      local p_table = DoElectedChange(room, target, self.name)
    else
      room:setPlayerMark(target, "_wk_heg__dingpin__xizhicai", 0)
      target:turnOver()
    end
  end,
}

local faen = fk.CreateTriggerSkill{
  name = "wk_heg__faen__xizhicai",
  anim_type = "offensive",
  events = {fk.TurnedOver, fk.ChainStateChanged},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and H.compareKingdomWith(player, target)) then return false end
    if event == fk.ChainStateChanged then
      return target.chained 
    else
      return (H.hasShownSkill(player, self) or player == target) and target:getHandcardNum() >= 2 and not target.faceup
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.TurnedOver then
      return player.room:askForSkillInvoke(target, self.name, nil, "#wk_heg__faen_turn-invoke")
    else
      return player.room:askForSkillInvoke(player, self.name, nil, "#wk_heg__faen_chained-invoke")
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.TurnedOver then
      -- target:throwAllCards("h")
      player.room:askForDiscard(target, 2, 2, false, self.name, false)
      target:turnOver()
    else
      target:drawCards(1, self.name)
    end
  end,
}
dingpin:addRelatedSkill(dingpin_delay)
Fk:addSkill(dingpin)
Fk:addSkill(faen)

local yuchen = fk.CreateTriggerSkill{
  name = "wk_heg__yuchen__xizhicai",
  events = {fk.EventPhaseStart},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and target ~= player and target.phase == Player.Finish and player:getHandcardNum() > 1) then return false end
    return #player.room.logic:getActualDamageEvents(1, function(e)
      return e.data[1].from == target
    end, Player.HistoryTurn) == 0
  end,
  on_cost = function (self, event, target, player, data)
    local cards = player.room:askForCard(player, 2, 2, false, self.name, true, ".", "#wk_heg__yuchen-give")
    if #cards == 2 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:obtainCard(target, self.cost_data, false, fk.ReasonGive)
    if not target.dead then
      room:setPlayerMark(target, "@@wk_heg__yuchen-turn", 1)
      target:gainAnExtraPhase(Player.Play)
    end
  end
}

local yuchen_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__yuchen_delay__xizhicai",
  events = {fk.EventPhaseEnd},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not (target:getMark("@@wk_heg__yuchen-turn") > 0 and target.phase == Player.Play and player:usedSkillTimes(yuchen.name, Player.HistoryTurn) > 0 and player:isAlive()) then return false end
    return #player.room.logic:getActualDamageEvents(1, function(e)
      return e.data[1].from == target
    end, Player.HistoryPhase) == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:damage{
      from = player,
      to = target,
      damage = 1,
      skillName = self.name,
    }
  end,
}

local mingsong = fk.CreateTriggerSkill{
  name = "wk_heg__mingsong__xizhicai",
  events = {fk.DamageCaused},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target and H.compareKingdomWith(player, target) and #target:getCardIds("e") > 0
      and table.find(player.room.alive_players, function(p) return target:canMoveCardsInBoardTo(p, "e") end) 
      and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and player.room.current ~= target
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function (p)
      return target:canMoveCardsInBoardTo(p, "e")
    end), Util.IdMapper)
    targets = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__mingsong-ask::"..target.id, self.name, true)
    if #targets > 0 then
      self.cost_data = targets[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    room:askForMoveCardInBoard(player, target, to, self.name, "e", target)
    local targets = {}
    local num = 999
    for _, p in ipairs(room.alive_players) do
      local n = p.hp
      if n <= num then
        if n < num then
          num = n
          targets = {}
        end
        if n < p.maxHp then
          table.insert(targets, p.id)
        end
      end
    end
    if #targets > 0 then
      local to_heal = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__mingsong-choose", self.name, true)
      if #to_heal > 0 then
        room:recover{
          who = room:getPlayerById(to_heal[1]),
          num = 1,
          recoverBy = player,
          skillName = self.name,
        }
      end
    end
    return true
  end,
}

yuchen:addRelatedSkill(yuchen_delay)
Fk:addSkill(yuchen)
Fk:addSkill(mingsong)

local fuyu = fk.CreateTriggerSkill{
  name = "wk_heg__fuyu__xizhicai",
  anim_type = "control",
  events = {fk.CardUseFinished, fk.CardRespondFinished},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and data.responseToEvent and data.responseToEvent.card
     and not H.compareKingdomWith(player.room:getPlayerById(data.responseToEvent.from), player)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(data.responseToEvent.from)
    if to.dead then return end
    if not to.chained then
      to:setChainState(true)
    -- if not table.find(room.alive_players, function (p) return H.compareKingdomWith(p, to) and not p.chained end) then
      -- H.askCommandTo(player, to, self.name, true)
    else
      room:damage{
        from = player,
        to = to,
        damage = 1,
        skillName = self.name,
      }
    end
  end,
}

Fk:addSkill(fuyu)

---@param object Card|Player
---@param markname string
---@param suffixes string[]
---@return boolean
local function hasMark(object, markname, suffixes)
  if not object then return false end
  for mark, _ in pairs(object.mark) do
    if mark == markname then return true end
    if mark:startsWith(markname .. "-") then
      for _, suffix in ipairs(suffixes) do
        if mark:find(suffix, 1, true) then return true end
      end
    end
  end
  return false
end

local shiju = fk.CreateTriggerSkill{
  name = "wk_heg__shiju__xizhicai",
  anim_type = "defensive",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p)
      return H.compareKingdomWith(p, player) end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "wk_heg__shiju_pro", self.name, true)
    if tos then
      local to = room:getPlayerById(tos[1])
      local choices = {}
      if player ~= to and not to:isNude() and player:getMark("wk_heg__jilun_alliance") > 0 then
        table.insert(choices, "wk_heg__shiju_change")
      end
      local card = Fk:cloneCard("slash")
      -- if not to:prohibitUse(Fk:cloneCard("slash")) and to:canUseCardTo() data.damage.from ~= to.id then
      if not to:prohibitUse(Fk:cloneCard("slash")) then
        table.insert(choices, "wk_heg__shiju_slash")
      end
      if #choices == 0 then return false end
      local choice = room:askForChoice(to, choices, self.name)
      if choice == "wk_heg__shiju_change" then
        local cards = room:askForCard(to, 1, 1, false, self.name, false, ".", "#wk_heg__shiju-give")
        room:obtainCard(player, cards, false, fk.ReasonGive)
        local mark_alliance = player:getMark("wk_heg__jilun_alliance")
        room:setPlayerMark(to, "wk_heg__jilun_alliance_change", mark_alliance)
        if mark_alliance == 1 then
          room:handleAddLoseSkills(to, "alliance1&", nil)
        elseif mark_alliance == 2 then
          room:handleAddLoseSkills(to, "alliance2&", nil)
        elseif mark_alliance == 3 then
          room:handleAddLoseSkills(to, "alliance3&", nil)
        end
      else
        -- local slash_targets = table.map(table.filter(room:getAlivePlayers(false), function(p)
        --   return p ~= to end), Util.IdMapper)
        -- local slash_tos = room:askForChoosePlayers(player, slash_targets, 1, 1, "wk_heg__shiju_slash_choose", self.name, true)
        -- if slash_tos then
        --   room:useVirtualCard("slash", nil, to, room:getPlayerById(slash_tos[1]), self.name, true)
        -- end
        local card
        local cards = {}
        local _pattern = ".|.|.|.|.|basic"
        if #room:getCardsFromPileByRule(_pattern, 1) == 0 then return false end
        while true do
          local id = room:getNCards(1)[1]
          room:moveCardTo(id, Card.Processing, nil, fk.ReasonJustMove, self.name)
          room:delay(300)
          local c = Fk:getCardById(id)
          if c:getTypeString() == "basic" or hasMark(c, "@@alliance", MarkEnum.CardTempMarkSuffix) then
            card = c
            break
          else
            table.insert(cards, id)
          end
        end
        room:moveCardTo(card.id, Player.Hand, to, fk.ReasonPrey, self.name, nil, true, player.id)
        cards = table.filter(cards, function(id) return room:getCardArea(id) == Card.Processing end)
        room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, nil, true, player.id)
      end
    end
  end,
}

Fk:addSkill(shiju)

local kenfeng = fk.CreateTriggerSkill{
  name = "wk_heg__kenfeng__xizhicai",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player ~= target and target.phase == Player.Finish
     and table.find(player.room.alive_players, function (p) return p:getHandcardNum() <= p.hp end)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function (p) return p:getHandcardNum() <= p.hp end), Util.IdMapper)
    if #targets > 0 then
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__kenfeng_choose")
      if #tos > 0 then
        local to = room:getPlayerById(tos[1])
        local cards = room:askForCard(to, 1, 1, true, self.name, true, ".|.|club", "#wk_heg__kenfeng_card")
        if #cards > 0 then
          room:moveCards({
            ids = cards,
            from = to.id,
            toArea = Card.DrawPile,
            moveReason = fk.ReasonJustMove,
            skillName = self.name,
            proposer = to.id,
            drawPilePosition = -1,
          })
          local draw_cards = to:drawCards(2, self.name)
          to:showCards(draw_cards)
          local need_give = {}
          for _, cid in ipairs(draw_cards) do
            local card = Fk:getCardById(cid)
            if card.suit == Card.Club then
              table.insertIfNeed(need_give, cid)
            end
          end
          local give_aim = table.map(table.filter(room.alive_players, function (p) return to:distanceTo(p) == 1 end), Util.IdMapper)
          if #need_give > 0 and #give_aim > 0 then
            local give_tos = room:askForChoosePlayers(to, give_aim, 1, 1, "#wk_heg__kenfeng_give", self.name, false)
            local give_to = room:getPlayerById(give_tos[1])
            room:obtainCard(give_to, need_give, false, fk.ReasonGive)
          end
        end
      end
    end
  end,
}

Fk:addSkill(kenfeng)


--- 交换副将
---@param room Room
---@param player ServerPlayer
---@param target ServerPlayer
---@return boolean
local function SwapTwoPlayersDeputy(room, player, target)
  if not (player.deputyGeneral and target.deputyGeneral) then return false end
  if player.deputyGeneral == "anjiang" then player:revealGeneral(true, true) end
  if target.deputyGeneral == "anjiang" then target:revealGeneral(true, true) end
  local general1 = player.deputyGeneral
  local general2 = target.deputyGeneral
 
  room:changeHero(player, "blank_shibing", false, true, false, false, false)
  room:changeHero(target, "blank_shibing", false, true, false, false, false)
  room:changeHero(player, general2, false, true, true, false, false)
  room:changeHero(target, general1, false, true, true, false, false)
  return true
end
 

local lingxie = fk.CreateTriggerSkill{
  name = "wk_heg__lingxie__xizhicai",
  anim_type = "special",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and table.find(player.room.alive_players, function (p) return H.compareKingdomWith(p, player) and p ~= player end)) then return false end
    local targets = {}
    player.room.logic:getActualDamageEvents(1, function(e)
      local damage = e.data[1]
      if player == damage.to then
        table.insertIfNeed(targets, damage.to.id)
      end
      return false
    end)
    return #targets > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function (p) return H.compareKingdomWith(p, player) end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 2, 2, "#wk_heg__lingxie-choose", self.name, false)
    local to1 = room:getPlayerById(tos[1])
    local to2 = room:getPlayerById(tos[2])
    SwapTwoPlayersDeputy(room, to1, to2)
    local to1general = Fk.generals[to1.general]
    local to1deputy = Fk.generals[to1.deputyGeneral]
    local to2general = Fk.generals[to2.general]
    local to2deputy = Fk.generals[to2.deputyGeneral]

    if ((to1general.maxHp + to1deputy.maxHp) % 2 == 1) and to1:getMark("@!yinyangfish") == 0 then
      H.addHegMark(room, to1, "yinyangfish")
    end
    if to1general:isCompanionWith(to1deputy) and to1:getMark("@!companion") == 0 then
      H.addHegMark(room, to1, "companion")
    end
    if ((to2general.maxHp + to2deputy.maxHp) % 2 == 1) and to2:getMark("@!yinyangfish") == 0 then
      H.addHegMark(room, to2, "yinyangfish")
    end
    if to2general:isCompanionWith(to2deputy) and to2:getMark("@!companion") == 0 then
      H.addHegMark(room, to2, "companion")
    end
  end,
}

local yanji = fk.CreateTriggerSkill{
  name = "wk_heg__yanji__xizhicai",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player ~= target and target.phase == Player.Play and not player:isKongcheng()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = player:getCardIds(Player.Hand)
    player:showCards(cards)
    local all_choices = {"wk_heg__yanji_black", "wk_heg__yanji_red"}
    local black = {}
    local red = {}
    for _, cid in ipairs(cards) do
      local card = Fk:getCardById(cid)
      if card.color == Card.Black then
        table.insertIfNeed(black, cid)
      end
      if card.color == Card.Red then
        table.insertIfNeed(red, cid)
      end
    end
    local choices = {}
    if #black > 0 and not player:prohibitUse(Fk:cloneCard("slash")) then
      table.insert(choices, "wk_heg__yanji_black")
    end
    if #red > 0 and not player:prohibitUse(Fk:cloneCard("peach")) then
      table.insert(choices, "wk_heg__yanji_red")
    end
    if #choices == 0 then return false end
    local choice = room:askForChoice(player, choices, self.name, nil, nil, all_choices)
    if choice == "wk_heg__yanji_black" then
      room:useVirtualCard("slash", black, player, target, self.name)
    else
      room:useVirtualCard("peach", red, player, target, self.name)
    end
    if (player.general == "wk_heg__zhaoyan" or player.deputyGeneral == "wk_heg__zhaoyan") and target:getMark("@wk_give_deputy") == 0 then
      if player.dead or target.dead then return end
      local isDeputy = H.inGeneralSkills(player, self.name)
      if isDeputy then
        DoGiveDeputy(room, player, target, "wk_heg__zhaoyan", player.kingdom, isDeputy == "d")
      end
      room:setPlayerMark(player, "wk_give_deputy_zhaoyan", 1)
    end
  end,
}

local yanji_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__yanji_delay__xizhicai",
  anim_type = "special",
  events = {fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    return target:getMark("wk_give_deputy_zhaoyan") == 1 and player:getMark("@wk_give_deputy") == "wk_heg__zhaoyan"
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    StopGiveDeputy(player.room, player, self.name)
    player.room:setPlayerMark(target, "wk_give_deputy_zhaoyan", 0)
  end,
}

yanji:addRelatedSkill(yanji_delay)
Fk:addSkill(yanji)
Fk:addSkill(lingxie)

--- 治流递归
---@param room Room
---@param player ServerPlayer
---@param num integer
local function AskForContinueZhiliu(room, player, num)
  local targets = table.map(table.filter(room.alive_players, function (p) return p ~= player end), Util.IdMapper)
  local tos, id = room:askForChooseCardsAndPlayers(player, num, num, targets, 1, 1, nil, "#wk_heg__zhiliu-give:::"..num, "wk_heg__zhiliu__xizhicai", true)
  if #tos > 0 then
    room:obtainCard(tos[1], id, false, fk.ReasonGive)
    local to = room:getPlayerById(tos[1])
    room:setPlayerMark(player, "wk_heg__zhiliu__xizhicai-turn", 1)
    if to:getMark("wk_heg__zhiliu__xizhicai-turn") == 0 then
      AskForContinueZhiliu(room, to, num + 1)
    end
  end
end

local zhiliu = fk.CreateTriggerSkill{
  name = "wk_heg__zhiliu__xizhicai",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Play and not player:isNude()
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    AskForContinueZhiliu(room, player, 1)
  end,
}

Fk:addSkill(zhiliu)

local qizhi = fk.CreateTriggerSkill{
  name = "wk_heg__qizhi__xizhicai",
  anim_type = "offensive",
  events = {fk.Damage},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and target == player.room.current and H.compareKingdomWith(player, target)) then return false end
    local room = player.room
    local damage_event = room.logic:getCurrentEvent()
    if not damage_event then return false end
    local x = target:getMark("wk_heg__qizhi-turn")
    if x == 0 then
      room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function (e)
        local reason = e.data[3]
        if reason == "damage" then
          local first_damage_event = e:findParent(GameEvent.Damage)
          if first_damage_event and first_damage_event.data[1].from == target then
            x = first_damage_event.id
            room:setPlayerMark(target, "wk_heg__qizhi-turn", x)
            return true
          end
        end
      end, Player.HistoryTurn)
    end
    return damage_event.id == x
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return p ~= data.to and not p:isNude() end), Util.IdMapper)
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__qizhi-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if self.cost_data then
      local to = room:getPlayerById(self.cost_data)
      local id = room:askForCardChosen(player, to, "he", self.name)
      room:throwCard(id, self.name, to, player)
      if not to.dead then
        to:drawCards(1, self.name)
      end
    end
  end,
}

local jinqu = fk.CreateTriggerSkill{
  name = "wk_heg__jinqu__xizhicai",
  anim_type = "drwacard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0  then
      for _, move in ipairs(data) do
        if move.from == player.id and move.moveReason ~= fk.ReasonUse and move.moveReason ~= fk.ReasonResonpse then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
              return true
            end
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) end), Util.IdMapper)
    if #targets == 0 then return end
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__jinqu-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if self.cost_data then
      local to = room:getPlayerById(self.cost_data)
      to:drawCards(2, self.name)
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, false)
      if turn_event == nil then return false end
      local end_id = turn_event.id
      local cards = {}
      U.getEventsByRule(room, GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.toArea == Card.DiscardPile then
            for _, info in ipairs(move.moveInfo) do
              local card_suit = Fk:getCardById(info.cardId, true).suit
              if room:getCardArea(info.cardId) == Card.DiscardPile and not table.contains(cards, card_suit) and card_suit ~= 0 then
                table.insertIfNeed(cards, card_suit)
              end
            end
          end
        end
        return false
      end, end_id)
      local discard_num = to:getHandcardNum() - #cards
      if discard_num > 0 then
        room:askForDiscard(to, discard_num, discard_num, false, self.name, false)
      end
    end
  end,
}

Fk:addSkill(qizhi)
Fk:addSkill(jinqu)

-- 三设

local ss_heg__qingxi__xizhicai = fk.CreateTriggerSkill {
  name = "ss_heg__qingxi__xizhicai",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target.phase == Player.Start and target ~= player then
      return player:getHandcardNum() > player.hp
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if player:getHandcardNum() > player.hp then
      local cards = room:askForDiscard(player, player:getHandcardNum() - player.hp, player:getHandcardNum() - player.hp,
        false, self.name, true, '.', "#ss_heg__qingxi-invoked:::" ..(player:getHandcardNum() - player.hp), true, true)
      if #cards > 0 then
        self.cost_data = cards
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data, self.name, player, player)
    local tocheck = {}
    room:setPlayerMark(player,"ss_heg__qingxi_canuse__xizhicai-phase",target.id)
    local usedcount = 0
    while not player.dead and usedcount < player.hp do
      local cardstouse = table.filter(self.cost_data,
        function(id) return room:getCardArea(id) == Card.DiscardPile and not table.contains(tocheck, id) end)
      if #cardstouse == 0 then room:setPlayerMark(player,"ss_heg__qingxi_canuse-phase",0) break end
      local use = U.askForUseRealCard(room, player, cardstouse, '.', self.name, "#ss_heg__qingxi-use::" .. target.id,
        { expand_pile = cardstouse, exclusive_targets = { target.id } , include_targets = { target.id }, bypass_distances = true}, true)
      if not use then room:setPlayerMark(player,"ss_heg__qingxi_canuse-phase",0) break end
      table.insertIfNeed(tocheck, use.card:getEffectiveId())
      room:useCard(use)
      usedcount = usedcount + 1
    end
    local mark = player:getTableMark("ss_heg__qingxi_distances-turn")
    table.insertIfNeed(mark, target.id)
    room:setPlayerMark(player, "ss_heg__qingxi_distances-turn", mark)
  end,
}

local ss_heg__qingxi__xizhicai_distance = fk.CreateTargetModSkill {
  name = "#ss_heg__qingxi_distance__xizhicai",
  bypass_distances = function(self, player, skill, card, to)
    return #to:getTableMark("ss_heg__qingxi_distances-turn") > 0 and
    table.contains(to:getTableMark("ss_heg__qingxi_distances-turn"), player.id)
  end,
}

local ss_heg__qingxi__xizhicai_prohibit = fk.CreateProhibitSkill {
  name = "#ss_heg__qingxi_prohibit__xizhicai",
  is_prohibited = function(self, from, to, card)
    return from:getMark("ss_heg__qingxi_canuse__xizhicai-phase")~=0 and to.id ~= from:getMark("ss_heg__qingxi_canuse__xizhicai-phase")
  end,
}

ss_heg__qingxi__xizhicai:addRelatedSkill(ss_heg__qingxi__xizhicai_distance)
ss_heg__qingxi__xizhicai:addRelatedSkill(ss_heg__qingxi__xizhicai_prohibit)
Fk:addSkill(ss_heg__qingxi__xizhicai)


-- 汤圆包
local tyjR__xieshou = fk.CreateTriggerSkill {
  name = "tyjR_heg__xieshou__xizhicai",
  events = { fk.Damaged },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target:isAlive() and player ~= target 
     and #table.filter(player.room.alive_players, function(p) return p.hp < target.hp end) == 0 
     and (player.faceup or not player.chained) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local all_choices = { "tyjR_heg__xieshou_link", "tyjR_heg__xieshou_cover", "Cancel" }
    local choices = {}
    if not player.chained then
      table.insert(choices, "tyjR_heg__xieshou_link")
    end
    if player.faceup then
      table.insert(choices, "tyjR_heg__xieshou_cover")
    end
    table.insert(choices, "Cancel")
    if #choices > 0 then
      local choice = room:askForChoice(player, choices, self.name, "#tyjR_heg__xieshou-invoke::" .. target.id, false, all_choices)
      if choice ~= "Cancel" then
        self.cost_data = choice
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, { target.id })
    if self.cost_data and self.cost_data ~= nil then
      if self.cost_data == "tyjR_heg__xieshou_link" then
        player:setChainState(true)
        target:drawCards(2, self.name)
        if target.faceup and target:isAlive() and player:isAlive() then
          -- local result = room:askForSkillInvoke(player, self.name, nil, "#tyjR_heg__xieshou_turn-invoke::" .. target.id)
          local result = room:askForSkillInvoke(target, self.name, nil, "#tyjR_heg__xieshou_turn-invoke::" .. player.id)
          if result then
            target:turnOver()
            -- room:handleAddLoseSkills(target, self.name, nil, true, false)
            player:drawCards(2, self.name)
          end
        end
      elseif self.cost_data == "tyjR_heg__xieshou_cover" then
        if player.faceup then
          player:turnOver()
        end
        target:drawCards(2, self.name)
        if not target.chained and target:isAlive() and player:isAlive() then
          -- local result = room:askForSkillInvoke(player, self.name, nil, "#tyjR_heg__xieshou_chain-invoke" .. target.id)
          local result = room:askForSkillInvoke(target, self.name, nil, "#tyjR_heg__xieshou_chain-invoke::" .. player.id)
          if result then
            target:setChainState(true)
            -- room:handleAddLoseSkills(target, self.name, nil, true, false)
            player:drawCards(2, self.name)
          end
        end
      end
    end
  end,
}
Fk:addSkill(tyjR__xieshou)


local tyjR__zhangyu = fk.CreateViewAsSkill {
  name = "tyjR_heg__zhangyu__xizhicai",
  pattern = "jink,nullification",
  prompt = function(self)
    if Fk.currentResponsePattern ~= nil and Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("jink")) then
      return "#tyjR_heg__zhangyu-jink";
    elseif Fk.currentResponsePattern ~= nil and Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("heg__nullification")) then
      return "#tyjR_heg__zhangyu-null";
    else
      return "#tyjR_heg__zhangyu-both";
    end
  end,
  interaction = function()
    local all_names = { "jink", "nullification" }
    local names1 = {}
    if #Self:getCardIds('h') >= Self:getMaxCards() then
      table.insert(names1, 'jink')
    end
    if #Self:getCardIds('h') <= #Self:getCardIds('e') then
      table.insert(names1, 'nullification')
    end
    local names = U.getViewAsCardNames(Self, "tyjR_heg__zhangyu__xizhicai", names1, {})
    if #names > 0 then
      return UI.ComboBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    if self.interaction.data then
      if self.interaction.data == "jink" then
        return #selected == 0 and Fk:currentRoom():getCardArea(to_select) == Player.Hand
      elseif self.interaction.data == "nullification" then
        return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeEquip
      else
        return false
      end
    end
    return false
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return end
    if self.interaction.data == "nullification" then
      self.interaction.data = "heg__nullification"
    end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return false
  end,
  enabled_at_response = function(self, player, response)
    if Fk.currentResponsePattern ~= nil then
      for _, name in ipairs({ "jink", "nullification" }) do
        local card = Fk:cloneCard(name)
        card.skillName = self.name
        if Exppattern:Parse(Fk.currentResponsePattern):match(card) then
          if name == "jink" then
            return #Self:getCardIds('h') >= Self:getMaxCards()
          elseif name == "nullification" then
            return #Self:getCardIds('h') <= #Self:getCardIds('e') and not response
          end
        end
      end
    end
  end,
}

Fk:addSkill(tyjR__zhangyu)

-- //////////////////////////////////
-- //////////////////////////////////

local xizhicai = General(extension, "ss_heg__xizhicai", "wei", 3, 3, General.Male)
xizhicai.hidden = true

local heixian = fk.CreateTriggerSkill{
  name = "ss_heg__heixian",
  anim_type = "special",
  events = {fk.EventPhaseStart, fk.Damaged},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return player:hasSkill(self) and player == target and player.phase == Player.Play
    else
      return player:hasSkill(self) and player == target
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local availablePlayerIds = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) and p ~= player and p.deputyGeneral ~= "blank_shibing" and p.deputyGeneral ~= "blank_nvshibing" end), Util.IdMapper)
    local all_name = {}
    local left_name = {}
    for _, id in ipairs(availablePlayerIds) do
      local p = room:getPlayerById(id)
      p:revealGeneral(true, true)
      table.insertIfNeed(all_name, p.deputyGeneral)
      table.insertIfNeed(left_name, p.deputyGeneral)
      -- H.removeGeneral(room, p, true)

      local orig = p.deputyGeneral
      if orig:startsWith("blank_") then return false end
      orig = Fk.generals[orig]
      local orig_skills = orig and orig:getSkillNameList() or {}
      local new_general = orig.gender == General.Male and "blank_shibing" or "blank_nvshibing"
      orig_skills = table.map(orig_skills, function(e)
        return "-" .. e
      end)
      room:handleAddLoseSkills(p, table.concat(orig_skills, "|"), nil, false)
      room:setPlayerProperty(p, "deputyGeneral", new_general)
      room:setPlayerMark(p, "__heg_deputy", new_general)
      p:filterHandcards()
    end
    for _, id in ipairs(availablePlayerIds) do
      local p = room:getPlayerById(id)
      local choice = room:askForChoice(player, left_name, self.name, "ss_heg__heixian-choose:::"..p.seat, nil, all_name)
      room:changeHero(p, choice, false, true, false, false, false)
      room:setPlayerProperty(p, "deputyGeneral", choice)
      room:setPlayerMark(p, "__heg_deputy", choice)
      p:hideGeneral(true)
      table.removeOne(left_name, choice)
    end
  end,
}

local baihou = fk.CreateTriggerSkill{
  name = "ss_heg__baihou",
  anim_type = "special",
  mute = true,
  refresh_events = {fk.EventAcquireSkill, fk.EventLoseSkill, fk.Deathed, fk.GeneralRevealed, fk.GeneralHidden, fk.AfterSkillEffect},
  can_refresh = function(self, event, target, player, data)
    if player ~= target then return false end
    if event == fk.Deathed then return player:hasSkill(self.name, true, true)
    elseif event == fk.EventAcquireSkill or event == fk.EventLoseSkill then return data == self
    elseif event == fk.AfterSkillEffect then return string.find(data.name, "__xizhicai")
    else return true end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterSkillEffect then
      -- target:revealGeneral()
      H.askForRevealGenerals(room, target, self.name, true, true, false, false)
    else
      local baihou_map = {}
      local xizis = table.filter(room.alive_players, function(p) return p:hasShownSkill(self) end)
      for _, p in ipairs(room.alive_players) do
        local will_attach = 0
        for _, xizi in ipairs(xizis) do
          if (xizi ~= p and H.compareKingdomWith(xizi, p) and H.getGeneralsRevealedNum(p) == 1) then
            will_attach = 1
            break
          end
        end
        baihou_map[p] = will_attach
      end

      for p, v in pairs(baihou_map) do
        if v ~= p:getMark("ss_heg__baihou_have") then
          if v == 1 then
            local skills = {}
            -- 现在考虑了技能标签
            if p.general ~= "anjiang" then
              for _, s in ipairs(Fk.generals[p.general]:getSkillNameList()) do
                local skill = Fk.skills[s]
                if skill and not skill.lordSkill and skill.name ~= "jianan" and skill.frequency <= 2 
                  and skill.name ~= "wk_heg__yulin" and skill.name ~= "heyi" and skill.name ~= "ld__fangyuan"
                  and skill.relate_to_place ~= "m" and skill.relate_to_place ~= "d" then
                  table.insertIfNeed(skills, s)
                end
              end
            end
            if p.deputyGeneral ~= "anjiang" then
              for _, s in ipairs(Fk.generals[p.deputyGeneral]:getSkillNameList()) do
                local skill = Fk.skills[s]
                if skill and not skill.lordSkill and skill.name ~= "jianan" and skill.frequency <= 2 
                  and skill.name ~= "wk_heg__yulin" and skill.name ~= "heyi" and skill.name ~= "ld__fangyuan"
                  and skill.relate_to_place ~= "m" and skill.relate_to_place ~= "d" then
                  table.insertIfNeed(skills, s)
                end
              end
            end
            for _, name in ipairs(skills) do
              -- 现在可能对了，现在不对，没判标签技能，导致失去的时候爆炸（上面已经判了，补判了个阵法）
              room:handleAddLoseSkills(p, name.."__xizhicai", nil, false, true)
            end
            room:setPlayerMark(p, "ss_heg__baihou_skillhave", #skills ~= 0 and skills or {})
          else
            local skill_todelete = p:getMark("ss_heg__baihou_skillhave")
            if #skill_todelete ~= 0 then
              for _, name in ipairs(skill_todelete) do
                room:handleAddLoseSkills(p, "-"..name.."__xizhicai", nil, false, true)
              end
              room:setPlayerMark(p, "ss_heg__baihou_skillhave", {})
            end
          end
          room:setPlayerMark(p, "ss_heg__baihou_have", v)
        end
      end
    end
  end,
}
xizhicai:addCompanions("hs__guojia")
xizhicai:addSkill(baihou)
xizhicai:addSkill(heixian)
Fk:loadTranslationTable{
  ["ss_heg__xizhicai"] = "戏志才", --魏国
  ["#ss_heg__xizhicai"] = "筹无画有",
  ["designer:ss_heg__xizhicai"] = "不能更改",
  ["ss_heg__heixian"] = "黑先",
  [":ss_heg__heixian"] = "锁定技，出牌阶段开始时或当你受到伤害后，你观看所有与你势力相同的其他角色的副将，然后暗置并重新分配。",
  ["ss_heg__baihou"] = "白后",
  [":ss_heg__baihou"] = "与你势力相同且仅明置一张武将牌的角色视为拥有其已明置武将牌上无技能标签技能的复制技能，并于发动此复制技能后明置一张武将牌。",

  ["ss_heg__heixian-choose"] = "黑先：分配所有与你势力相同其他角色的副将，当前分配位置为 %arg 号位",

  ["ss_heg__heixian1"] = "辅佐明君，从一而终。",
  ["ss_heg__heixian2"] = "吾于此生，竭尽所能。",
  ["ss_heg__baihou1"] = "一筹一划，一策一略。",
  ["ss_heg__baihou2"] = "主公之忧，吾之所思也。",
  ["~ss_heg__xizhicai"] = "为何……不再给我……一点点时间……",
  
  -- 国标
  ["jianxiong__xizhicai"] = "奸雄(暗)",
  [":jianxiong__xizhicai"] = "当你受到伤害后，你可获得对你造成伤害的牌。",

  ["fankui__xizhicai"] = "反馈(暗)",
  [":fankui__xizhicai"] = "当你受到伤害后，你可获得伤害来源一张牌。",
  ["ex_guicai__xizhicai"] = "鬼才(暗)",
  [":ex_guicai__xizhicai"] = "一名角色的判定牌生效前，你可打出一张牌代替之。",

  ["hs__ganglie__xizhicai"] = "刚烈(暗)",
  [":hs__ganglie__xizhicai"] = "当你受到伤害后，你可判定，若结果为：红色，你对来源造成1点伤害；黑色，你弃置来源的一张牌。",

  ["ex_tuxi__xizhicai"] = "突袭(暗)",
  [":ex_tuxi__xizhicai"] = "摸牌阶段，你可少摸任意张牌并选择至多等量名其他角色，获得这些角色各一张手牌。",
  
  ["hs__luoyi__xizhicai"] = "裸衣(暗)",
  [":hs__luoyi__xizhicai"] = "摸牌阶段结束时，你可弃置一张牌，令你于此回合内执行【杀】或【决斗】的效果造成伤害时，此伤害+1。",

  ["tiandu__xizhicai"] = "天妒(暗)",
  [":tiandu__xizhicai"] = "当你的判定牌生效后，你可获得之。",
  ["hs__yiji__xizhicai"] = "遗计(暗)",
  [":hs__yiji__xizhicai"] = "当你受到伤害后，你可观看牌堆顶的两张牌并分配。",

  ["qingguo__xizhicai"] = "倾国(暗)",
  [":qingguo__xizhicai"] = "你可将黑色手牌当【闪】使用或打出。",
  ["hs__luoshen__xizhicai"] = "洛神(暗)",
  [":hs__luoshen__xizhicai"] = "准备阶段开始时，你可进行判定，你可重复此流程，直到判定结果为红色，然后你获得所有黑色的判定牌。",

  ["hs__shensu__xizhicai"] = "神速(暗)",
  [":hs__shensu__xizhicai"] = "①判定阶段开始前，你可跳过此阶段和摸牌阶段视为使用普【杀】。②出牌阶段开始前，你可跳过此阶段并弃置一张装备牌视为使用普【杀】。③弃牌阶段开始前，你可跳过此阶段并失去1点体力视为使用普【杀】。",

  ["hs__duanliang__xizhicai"] = "断粮(暗)",
  [":hs__duanliang__xizhicai"] = "你可将一张不为锦囊牌的黑色牌当【兵粮寸断】使用（无距离关系的限制），若你至目标对应的角色的距离大于2，此技能于此阶段内无效。",
  
  ["hs__jushou__xizhicai"] = "据守(暗)",
  [":hs__jushou__xizhicai"] = "结束阶段，你可摸X张牌（X为势力数），然后弃置一张手牌，若以此法弃置的牌为装备牌，则改为你使用之。若X大于2，则你将武将牌叠置。",
  
  ["hs__qiangxi__xizhicai"] = "强袭(暗)",
  [":hs__qiangxi__xizhicai"] = "出牌阶段限一次，你可以失去1点体力或弃置一张武器牌，并选择一名其他角色，对其造成1点伤害。",

  ["quhu__xizhicai"] = "驱虎(暗)",
  [":quhu__xizhicai"] = "出牌阶段限一次，你可与一名体力值大于你的角色拼点，若你赢，你令其对其攻击范围内你选择的一名角色造成1点伤害；若你没赢，其对你造成1点伤害。",
  ["hs__jieming__xizhicai"] = "节命(暗)",
  [":hs__jieming__xizhicai"] = "当你受到伤害后，你可令一名角色将手牌补至X张（X为其体力上限且最多为5）。",
  
  ["xingshang__xizhicai"] = "行殇(暗)",
  [":xingshang__xizhicai"] = "当一名角色死亡后，你可以获得其所有牌。",
  ["hs__fangzhu__xizhicai"] = "放逐(暗)",
  [":hs__fangzhu__xizhicai"] = "当你受到伤害后，你可令一名其他角色选择一项：1.摸X张牌并叠置；2.弃置X张牌并失去1点体力。（X为你已损失的体力值）",

  ["hs__xiaoguo__xizhicai"] = "骁果(暗)",
  [":hs__xiaoguo__xizhicai"] = "其他角色的结束阶段，你可弃置一张基本牌，然后其选择一项：1.弃置一张装备牌，然后你摸一张牌；2.你对其造成1点伤害。",

  ["@@hs__duanliang__xizhicai-phase"] = "断粮 失效",

  -- 阵势变权
  ["ld__tuntian__xizhicai"] = "屯田(暗)",
  [":ld__tuntian__xizhicai"] = "当你于回合外失去牌后，你可判定：若结果不为<font color='red'>♥</font>，你可将弃牌堆里的此判定牌置于武将牌上（称为“田”）。你至其他角色的距离-X（X为“田”数）。",
  
  ["ld__huyuan__xizhicai"] = "护援(暗)",
  [":ld__huyuan__xizhicai"] = "结束阶段，你可选择：1.将一张手牌交给一名角色；2.将一张装备牌置入一名角色的装备区，然后弃置场上的一张牌。",

  ["xunxun__xizhicai"] = "恂恂(暗)",
  [":xunxun__xizhicai"] = "摸牌阶段开始时，你可以观看牌堆顶的四张牌，将其中两张牌以任意顺序置于牌堆顶，其余以任意顺序置于牌堆底。",
  ["wangxi__xizhicai"] = "忘隙(暗)",
  [":wangxi__xizhicai"] = "当你对其他角色造成1点伤害后，或当你受到其他角色造成的1点伤害后，你可以与其各摸一张牌。",
  
  ['hengjiang__xizhicai'] = '横江(暗)',
  [':hengjiang__xizhicai'] = '当你受到伤害后，你可以令当前回合角色本回合手牌上限-X（X为其装备区内牌数且至少为1）。' ..
    '然后若其本回合弃牌阶段内没有弃牌，你将手牌摸至体力上限。',

  ["ld__qice__xizhicai"] = "奇策(暗)",
  [":ld__qice__xizhicai"] = "出牌阶段限一次，你可将所有手牌当任意一张普通锦囊牌使用，你不能以此法使用目标数大于X的牌（X为你的手牌数），然后你可变更副将。",
  ["ld__zhiyu__xizhicai"] = "智愚(暗)",
  [":ld__zhiyu__xizhicai"] = "每当你受到一次伤害后，你可以摸一张牌，然后展示所有手牌，若颜色均相同，伤害来源弃置一张手牌。",
  
  ["ld__wanwei__xizhicai"] = "挽危(暗)",
  [":ld__wanwei__xizhicai"] = "当你的牌被其他角色弃置或获得时，你可改为你选择的等量的牌。",

  ["ld__zhengbi__xizhicai"] = "征辟(暗)",
  [":ld__zhengbi__xizhicai"] = "出牌阶段开始时，你可选择一项：1.选择一名没有势力的角色，直至其确定势力或此回合结束，你对其使用牌无距离与次数限制；2.将一张基本牌交给一名已确定势力的角色，然后其交给你一张非基本牌或两张基本牌。",
  
  ['ld__jieyue__xizhicai'] = '节钺(暗)',
  [':ld__jieyue__xizhicai'] = '准备阶段，你可将一张手牌交给不是魏势力或没有势力的一名角色，对其发起“军令”。若其：执行，你摸一张牌；不执行，摸牌阶段，你令额定摸牌数+3。',
  
  ["huibian__xizhicai"] = "挥鞭(暗)",
  [":huibian__xizhicai"] = "出牌阶段限一次，你可选择一名魏势力角色和另一名已受伤的魏势力角色，若如此做，你对前者造成1点伤害，令其摸两张牌，然后后者回复1点体力。",

  
  ["@@ld__qice_transform__xizhicai"] = "奇策 已变更",

  -- 不臣篇
  ["quanjin__xizhicai"] = "劝进(暗)",
  [":quanjin__xizhicai"] = "出牌阶段限一次，你可将一张手牌交给一名此阶段受到过伤害的角色，对其发起“军令”。若其执行，你摸一张牌；若其不执行，你将手牌摸至与手牌最多的角色相同（最多摸五张）。",
  ["zaoyun__xizhicai"] = "凿运(暗)",
  [":zaoyun__xizhicai"] = "出牌阶段限一次，你可选择一名与你势力不同且你至其距离大于1的角色并弃置X张手牌（X为你至其的距离-1），令你至其的距离此回合视为1，然后你对其造成1点伤害。",
  
  ["ld__juejue__xizhicai"] = "决绝(暗)",
  [":ld__juejue__xizhicai"] = "①弃牌阶段开始时，你可失去1点体力，若如此做，此阶段结束时，若你于此阶段内弃置过牌，你令所有其他角色选择一项：1.将X张手牌置入弃牌堆；2.受到你造成的1点伤害（X为你于此阶段内弃置的牌数）；②你杀死与你势力相同的角色不执行奖惩。",
  
  ["ld__qiuan__xizhicai"] = "求安(暗)",
  [":ld__qiuan__xizhicai"] = "当你受到伤害时，若没有“函”，你可将造成此伤害的牌置于武将牌上，称为“函”，然后防止此伤害。",
  
  ["ld__bushi__xizhicai"] = "布施(暗)",
  [":ld__bushi__xizhicai"] = "一名角色的结束阶段，若你于此回合内造成或受到过伤害，你可移去一张“米”，令至多X名角色各摸一张牌（X为你的体力上限），以此法摸牌的角色可依次将一张牌置于你武将牌上，称为“米”。",
  ["ld__midao__xizhicai"] = "米道(暗)",
  [":ld__midao__xizhicai"] = "①当你明置此武将牌后，你摸两张牌，然后将两张牌置于武将牌上，称为“米”②一名角色的判定牌生效前，你可以打出一张“米”替换之。",
  
  ["ld__jinfa__xizhicai"] = "矜伐(暗)",
  [":ld__jinfa__xizhicai"] = "出牌阶段限一次，你可弃置一张牌并选择一名其他角色，令其选择一项：1.令你获得其一张牌；2.交给你一张装备牌，若此装备牌为♠，其视为对你使用一张【杀】。",
  
  ["ld__chenglue__xizhicai"] = "成略(暗)",
  [":ld__chenglue__xizhicai"] = "当与你势力相同的角色使用牌指定目标后，若目标数大于1，你可令其摸一张牌。若如此做且你受到过此牌造成的伤害，此牌结算完成后，你可令一名与你势力相同且没有国战标记的角色获得一个“阴阳鱼”标记。",


  -- 十周年
  ["ty_heg__wanggui__xizhicai"] = "望归(暗)",
  [":ty_heg__wanggui__xizhicai"] = "每回合限一次，当你造成或受到伤害后，若你：仅明置此武将牌，你可对与你势力不同的一名角色造成1点伤害；武将牌均明置，"..
  "你可令所有与你势力相同的角色各摸一张牌。",
  ["ty_heg__xibing__xizhicai"] = "息兵(暗)",
  [":ty_heg__xibing__xizhicai"] = "当其他角色于其出牌阶段内使用黑色【杀】或黑色普通锦囊牌指定唯一目标后，若其于此回合内未使用过黑色【杀】或黑色普通锦囊牌，你可令其将手牌摸至体力值"..
  "（至多摸至五张），然后若你与其均明置了所有武将牌，则你可暗置你与其各一张武将牌且本回合不能明置以此法暗置的武将牌。若其因此摸牌，其本回合不能使用手牌。",
  
  ["ty_heg__deshao__xizhicai"] = "德劭(暗)",
  [":ty_heg__deshao__xizhicai"] = "每回合限X次（X为你的体力值），当其他角色使用黑色牌指定你为唯一目标后，若其已明置的武将牌数不大于你，你可弃置其一张牌。",
  ["ty_heg__mingfa__xizhicai"] = "明伐(暗)",
  [":ty_heg__mingfa__xizhicai"] = "出牌阶段限一次，你可以选择与你势力不同或未确定势力的一名其他角色，其下个回合结束时，若其手牌数：小于你，你对其造成1点伤害并获得其一张手牌；"..
  "不小于你，你摸至与其手牌数相同（最多摸五张）。",
  
  ["ty_heg__weicheng__xizhicai"] = "伪诚(暗)",
  [":ty_heg__weicheng__xizhicai"] = "你交给其他角色手牌，或你的手牌被其他角色获得后，若你的手牌数小于体力值，你可以摸一张牌。",
  ["ty_heg__daoshu__xizhicai"] = "盗书(暗)",
  [":ty_heg__daoshu__xizhicai"] = "出牌阶段限一次，你可以选择一名其他角色并选择一种花色，然后获得其一张手牌。若此牌与你选择的花色："..
  "相同，你对其造成1点伤害且此技能视为未发动过；不同，你交给其一张其他花色的手牌（若没有需展示所有手牌）。",

  ["ty_heg__jianguo__xizhicai"] = "谏国(暗)",
  [":ty_heg__jianguo__xizhicai"] = "出牌阶段限一次，你可选择一项：1. 令一名角色摸一张牌，然后弃置半数手牌；"..
  "2. 令一名角色弃置一张牌，然后摸半数手牌数量的牌。（均向下取整且至多为5）",
  ["ty_heg__qingshid__xizhicai"] = "倾势(暗)",
  [":ty_heg__qingshid__xizhicai"] = "当你于回合内使用【杀】或锦囊牌指定其他角色为目标后，若此牌是你本回合使用的第X张牌（X为你的手牌数且至多为5），你可以对其中一名目标角色造成1点伤害。",

  ["@@ty_heg__mingfa_delay__xizhicai"] = "明伐",

  -- 海外服
  ["danlao__xizhicai"] = "啖酪(暗)",
  [":danlao__xizhicai"] = "当一个锦囊指定了包括你在内的多个目标，你可以摸一张牌，若如此做，该锦囊对你无效。",
  ["jilei__xizhicai"] = "鸡肋(暗)",
  [":jilei__xizhicai"] = "当你受到伤害后，你可以声明一种牌的类别（基本牌、锦囊牌、装备牌），对你造成伤害的角色不能使用、打出或弃置该类别的手牌直到回合结束。",
  
  ["os_heg__tanfeng__xizhicai"] = "探锋(暗)",
  [":os_heg__tanfeng__xizhicai"] = "准备阶段开始时，你可弃置一名没有势力或势力与你不同的角色区域内的一张牌，然后其选择是否受到你造成的1点火焰伤害，令你跳过一个阶段。",

  -- 日月
  ["wk_heg__poyuan__xizhicai"] = "破垣(暗)",
  [":wk_heg__poyuan__xizhicai"] = "①当你对其他角色造成伤害后，你可弃置其一张装备区内的牌；②当你于回合内首次对大势力角色造成伤害时，此伤害+1。",
  ["wk_heg__choulue__xizhicai"] = "筹略(暗)",
  [":wk_heg__choulue__xizhicai"] = "①当你受到伤害后，若你的“阴阳鱼”标记数小于你体力上限，你可获得一个“阴阳鱼”标记；②当与你势力相同的角色使用普通锦囊牌指定唯一目标后，你可移去一个“阴阳鱼”标记，令此牌结算两次。",
  
  ["wk_heg__liance__xizhicai"] = "连策(暗)",
  [":wk_heg__liance__xizhicai"] = "其他角色的出牌阶段结束时，若其于此阶段内使用过同名普通锦囊牌，你可弃置一张牌，令其选择是否视为使用此回合内其使用过的其中一张同名牌。",
  ["wk_heg__shilun__xizhicai"] = "世论(暗)",
  [":wk_heg__shilun__xizhicai"] = "当你受到伤害后，你可展示所有手牌并弃至每种花色各一张，然后若你的手牌：包含四种花色，你可移动场上一张牌；不包含四种花色，你从牌堆中检索并获得手牌中没有的花色牌各一张。",

  ["wk_heg__dingpin__xizhicai"] = "定品(暗)",
  [":wk_heg__dingpin__xizhicai"] = "结束阶段，你可叠置并令一名其他角色于此回合结束后执行一个额外回合，此额外回合：1.准备阶段，若其与你势力相同，其推举；2.回合结束时，其叠置。<br />" ..
  "<font color = 'gray'>推举：推举角色展示一张与其势力相同的武将牌，每名与其势力相同的角色选择是否将此武将牌替换其已明置的主将或副将。" ..
  "若有角色选择替换，称为该角色<u>选用</u>，停止对后续角色的询问，结束推举流程。</font>",
  ["wk_heg__faen__xizhicai"] = "法恩(暗)",
  [":wk_heg__faen__xizhicai"] = "与你势力相同的角色：1.横置后，你可令其摸一张牌；2.叠置后，其可弃置两张手牌，平置。",

  
  ["wk_heg__yuchen__xizhicai"] = "驭臣(暗)",
  [":wk_heg__yuchen__xizhicai"] = "其他角色的结束阶段，若其本回合未造成过伤害，你可以交给其两张牌，令其执行一个额外的出牌阶段，若如此做，此额外的阶段结束时，若其于此阶段未造成过伤害，你对其造成1点伤害。",
  ["wk_heg__mingsong__xizhicai"] = "明讼(暗)",
  [":wk_heg__mingsong__xizhicai"] = "每回合限一次，与你势力相同的角色于其回合外造成伤害时，你可以移动其装备区里的一张牌，防止此伤害，然后你可令一名体力值最小的角色回复1点体力。",

  ["wk_heg__fuyu__xizhicai"] = "伏御(暗)",
  [":wk_heg__fuyu__xizhicai"] = "当你响应与你势力不同角色使用的牌后，你可令其横置，若其已横置，则改为你对其造成1点伤害。",

  ["wk_heg__shiju__xizhicai"] = "势举(暗)",
  [":wk_heg__shiju__xizhicai"] = "当你受到伤害后，你可以令一名与你势力相同的角色选择一项：1.交给你一张牌，其“合纵”规则改为与你相同直至其回合结束；2.检索并获得一张基本牌或带有“合纵”标记的牌。",
  
  ["wk_heg__kenfeng__xizhicai"] = "垦丰(暗)",
  [":wk_heg__kenfeng__xizhicai"] = "其他角色的结束阶段，你可令一名手牌数不大于体力值的角色选择是否将一张♣牌置于牌堆底并摸两张牌，若如此做，其展示以此法获得的所有牌并将其中的♣牌交给一名其距离为1的角色。",
  
  -- ["wk_heg__bixiong__xizhicai"] = "避凶(暗)",
  -- [":wk_heg__bixiong__xizhicai"] = "与你距离为1的角色受到伤害后，你可叠置并展示一张手牌，直至此回合结束此花色的牌对所有与你势力相同的角色无效",
    
  ["wk_heg__lingxie__xizhicai"] = "令协(暗)",
  [":wk_heg__lingxie__xizhicai"] = "每回合结束时，若你此回合内受到过伤害，你可令两名你势力相同的角色交换副将并重新结算对应的国战标记。",
  ["wk_heg__yanji__xizhicai"] = "严纪(暗)",
  [":wk_heg__yanji__xizhicai"] = "其他角色的出牌阶段开始时，你可以展示所有手牌并选择将其中所有红色/黑色牌当【桃】/【杀】对其使用，然后你借调此武将牌于其至你回合开始。<br />"..
  "<font color = 'orange'>借调：借调角色执行借调流程时，移除对应的武将牌并将之置于目标角色的借调区内，视为该角色拥有此武将牌，借调区内的武将牌不为主副将且不能被移除、暗置和变更。"..
  "借调结束后，目标角色选择借调武将牌原本所属国家所有角色的一张士兵牌，令此士兵牌变更为借调武将牌。</font>",

  ["wk_heg__zhiliu__xizhicai"] = "治流(暗)",
  [":wk_heg__zhiliu__xizhicai"] = "出牌阶段开始时，你可将一张牌交给一名其他角色，然后若以此法获得牌的角色本回合未以此法失去过牌，其可以重复牌数+1的此流程。",

  ["wk_heg__qizhi__xizhicai"] = "奇制(暗)",
  [":wk_heg__qizhi__xizhicai"] = "与你势力相同的角色于其回合内首次造成伤害后，你可以弃置不为受伤角色的一张牌，然后以此法失去牌的角色摸一张牌。",
  ["wk_heg__jinqu__xizhicai"] = "进趋(暗)",
  [":wk_heg__jinqu__xizhicai"] = "每回合限一次，当你不因使用或打出而失去牌后，你可令一名与你势力相同的角色摸两张牌，然后其将手牌弃至X张（X为此回合进入弃牌堆的牌花色数）。",

  -- 紫星
  ["zx_heg__fuli__xizhicai"] = "复礼(暗)",
  [":zx_heg__fuli__xizhicai"] = "与你势力相同角色的摸牌阶段，其可多摸一张牌，若如此做，此阶段结束时，其展示并交给你一张牌且本回合不能使用或打出与此牌花色相同的牌。",
  ["zx_heg__fengwu__xizhicai"] = "风物(暗)",
  [":zx_heg__fengwu__xizhicai"] = "出牌阶段限一次，你可令至多三名角色依次选择是否使用一张牌，然后若本回合所有花色的牌均被使用过，你摸两张牌并回复1点体力。",
  
  ["zx_heg__tongjun__xizhicai"] = "恸君(暗)",
  [":zx_heg__tongjun__xizhicai"] = "大势力角色进入濒死状态时，你可选择你与其各一张手牌，然后你交换这两张牌。",

  --三设吧
  ["ss_heg__qingxi__xizhicai"]="倾袭(暗)",
  [":ss_heg__qingxi__xizhicai"]="其他角色的准备阶段，你可以将手牌弃置至X张，然后仅对其使用至多X张以此法弃置的牌（X为你的体力值）。若如此做，其本回合对你使用牌无距离限制。",

  --汤圆包
  ["tyjR_heg__xieshou__xizhicai"] = "协守(暗)",
  [":tyjR_heg__xieshou__xizhicai"] = "每回合限一次，其他角色受到伤害后，若其的体力值为全场最小且若你未横置/叠置，你可横置/叠置并令其摸两张牌，然后其可执行另一项令你摸两张牌。",

  ["tyjR_heg__zhangyu__xizhicai"]="嶂御(暗)",
  [":tyjR_heg__zhangyu__xizhicai"]="若你的手牌数：不大于装备区内的牌数，你可以将一张装备牌当【无懈可击·国】使用；不小于手牌上限，你可以将一张手牌当【闪】使用。",
  
  -- 新月
  -- ["zhenlie__xizhicai"] = "贞烈(暗)",
  -- [":zhenlie__xizhicai"] = "当你成为其他角色使用【杀】或普通锦囊牌的目标后，你可以失去1点体力使此牌对你无效，然后你弃置其一张牌。",
  -- ["miji__xizhicai"] = "秘计(暗)",
  -- [":miji__xizhicai"] = "结束阶段，你可以摸X张牌（X为你已损失的体力值），然后你可以将等量的手牌分配给其他角色。",

  -- ["fk_heg__zhanmeng__xizhicai"] = "占梦(暗)",
  -- [":fk_heg__zhanmeng__xizhicai"] = "你的回合内，你使用牌时，可以执行以下一项（每回合每项各限一次）：<br>"..
  -- "1.上一回合内，若没有同名牌被使用，你获得一张非伤害牌。<br>"..
  -- "2.下一回合内，当同名牌首次被使用后，你获得一张伤害牌。<br>"..
  -- "3.令一名其他角色弃置一张牌。",

  -- ["fk_heg__jiezhong__xizhicai"] = "诫忠(暗)",
  -- [":fk_heg__jiezhong__xizhicai"] = "与你势力相同角色的结束阶段，若其手牌数小于其手牌上限，你可令其摸一张牌，然后其使用一张牌或将一张牌置于牌堆顶。",
  -- ["fk_heg__qingshiz__xizhicai"] = "清识(暗)",
  -- [":fk_heg__qingshiz__xizhicai"] = "出牌阶段限一次，你可观看一名其他角色所有手牌，若其中有【杀】，其攻击范围内与你势力相同的角色各摸一张牌。",
}


local ss_heg__caoxiu = General:new(extension, "ss_heg__caoxiu", "wei", 4, 4)

    local ss_heg__qingxi = fk.CreateTriggerSkill {
      name = "ss_heg__qingxi",
      events = { fk.EventPhaseStart },
      can_trigger = function(self, event, target, player, data)
        if player:hasSkill(self) and target.phase == Player.Start and target ~= player then
          return player:getHandcardNum() > player.hp
        end
      end,
      on_cost = function(self, event, target, player, data)
        local room = player.room
        if player:getHandcardNum() > player.hp then
          local cards = room:askForDiscard(player, player:getHandcardNum() - player.hp, player:getHandcardNum() - player.hp,
            false, self.name, true, '.', "#ss_heg__qingxi-invoked:::" ..(player:getHandcardNum() - player.hp), true, true)
          if #cards > 0 then
            self.cost_data = cards
            return true
          end
        end
      end,
      on_use = function(self, event, target, player, data)
        local room = player.room
        room:throwCard(self.cost_data, self.name, player, player)
        local tocheck = {}
        room:setPlayerMark(player,"ss_heg__qingxi_canuse-phase",target.id)
        local usedcount = 0
        while not player.dead and usedcount < player.hp do
          local cardstouse = table.filter(self.cost_data,
            function(id) return room:getCardArea(id) == Card.DiscardPile and not table.contains(tocheck, id) end)
          if #cardstouse == 0 then room:setPlayerMark(player,"ss_heg__qingxi_canuse-phase",0) break end
          local use = U.askForUseRealCard(room, player, cardstouse, '.', self.name, "#ss_heg__qingxi-use::" .. target.id,
            { expand_pile = cardstouse, exclusive_targets = { target.id } , include_targets = { target.id }, bypass_distances = true}, true)
          if not use then room:setPlayerMark(player,"ss_heg__qingxi_canuse-phase",0) break end
          table.insertIfNeed(tocheck, use.card:getEffectiveId())
          room:useCard(use)
          usedcount = usedcount + 1
        end
        local mark = player:getTableMark("@@ss_heg__qingxi_distances-turn")
        table.insertIfNeed(mark, target.id)
        room:setPlayerMark(player, "@@ss_heg__qingxi_distances-turn", mark)
      end,
    }
    
    local ss_heg__qingxi_distance = fk.CreateTargetModSkill {
      name = "#ss_heg__qingxi_distance",
      bypass_distances = function(self, player, skill, card, to)
        return #to:getTableMark("@@ss_heg__qingxi_distances-turn") > 0 and
        table.contains(to:getTableMark("@@ss_heg__qingxi_distances-turn"), player.id)
      end,
    }

    local ss_heg__qingxi_prohibit = fk.CreateProhibitSkill {
      name = "#ss_heg__qingxi_prohibit",
      is_prohibited = function(self, from, to, card)
        return from:getMark("ss_heg__qingxi_canuse-phase")~=0 and to.id ~= from:getMark("ss_heg__qingxi_canuse-phase")
      end,
    }

    ss_heg__qingxi:addRelatedSkill(ss_heg__qingxi_distance)
    ss_heg__qingxi:addRelatedSkill(ss_heg__qingxi_prohibit)
    ss_heg__caoxiu:addSkill(ss_heg__qingxi)
    
    Fk:loadTranslationTable {
      ["ss_heg__caoxiu"] = "曹休",
      ["#ss_heg__caoxiu"] = "千烽贯烬",
      ["designer:ss_heg__caoxiu"] = "王日天",
      ["cv:ss_heg__caoxiu"] = "官方",
      ["illustrator:ss_heg__caoxiu"] = "官方",
    
      ["ss_heg__qingxi"] = "倾袭",
      [":ss_heg__qingxi"] = "其他角色的准备阶段，你可以将手牌弃置至X张，然后仅对其使用至多X张以此法弃置的牌（X为你的体力值）。若如此做，其本回合对你使用牌无距离限制。",
    
      ["#ss_heg__qingxi-invoked"] = "是否弃置 %arg 张牌以发动 倾袭 ？",
      ["#ss_heg__qingxi-use"] = "倾袭：你可以对 %dest 使用一张弃置的牌",
      ["@@ss_heg__qingxi_distances-turn"] = "已倾袭",
    
      ["$ss_heg__qingxi1"] = "此残兵败将，胜之若儿戏耳！",
      ["$ss_heg__qingxi2"] = "有休在此，主公何虑？哈哈哈哈！",
      ["~ss_heg__caoxiu"] = "此战大败，休甚是羞惭啊……",
    }

local qinmi = General(extension, "ss_heg__qinmi", "shu", 3, 3, General.Male)
local zhuandui = fk.CreateTriggerSkill{
  name = "ss_heg__zhuandui",
  frequency = Skill.Compulsory,
  anim_type = "special",
  events = {fk.CardUsing},
  can_trigger = function (self, event, target, player, data)
    local room = player.room
    if not (player:hasSkill(self) and room.current == player and player == target) then return false end
    local first = room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e) 
      local use = e.data[1]
      return use.from == player.id
    end, Player.HistoryTurn)
    if #first > 0 and first[1].data[1] == data then 
      self.cost_data = data.card.number
      return true 
    end

    local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
    if turn_event == nil then return false end
    local use_event = room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
    if use_event == nil then return false end
    local mark = target:getTableMark("ss_heg__zhuandui-turn")
    if table.contains(mark, use_event.id) then
      return #mark > 1 and mark[2] == use_event.id
    end
    if #mark > 1 then return false end
    mark = {}
    room.logic:getEventsOfScope(GameEvent.UseCard, 2, function(e)
      local use = e.data[1]
      if use.from == player.id then
        table.insert(mark, e.id)
        return true
      end
      return false
    end, Player.HistoryTurn)
    room:setPlayerMark(target, "ss_heg__zhuandui-turn", mark)
    if not (#mark > 1 and mark[2] == use_event.id) then return false end
    local events = room.logic.event_recorder[GameEvent.UseCard] or {}
    local last_find = false
    for i = #events, 1, -1 do
      local e = events[i]
      if e.id < turn_event.id then return false end
      if e.id == use_event.id then
        last_find = true
      elseif last_find then
        if e.data[1].card.number < data.card.number and e.data[1].card.number ~= 0 then
          self.cost_data = -1
          return true
        end
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    if self.cost_data ~= -1 then
      local room = player.room
      room:setPlayerMark(player, "@ss_heg__zhuandui_forbidden-turn", self.cost_data)
      for _, p in ipairs(room.alive_players) do
        room:setPlayerMark(p, "ss_heg__zhuandui_forbidden-turn", self.cost_data)
      end
    else
      player:drawCards(1, self.name)
    end
  end,
}

local zhuandui_prohibit = fk.CreateProhibitSkill{
  name = "#ss_heg__zhuandui_prohibit",
  prohibit_use = function(self, player, card)
    local mark = player:getMark("ss_heg__zhuandui_forbidden-turn")
    return not card:isVirtual() and card.number < mark
  end,
  prohibit_response = function(self, player, card)
    local mark = player:getMark("ss_heg__zhuandui_forbidden-turn")
    return not card:isVirtual() and card.number < mark
  end,
}

local jianzheng = fk.CreateTriggerSkill{
  name = "ss_heg__jianzheng",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room:getAlivePlayers(false), function(p) return H.compareKingdomWith(p, player, true) end), Util.IdMapper)
    return player:hasSkill(self) and H.compareKingdomWith(player, target) and target.phase == Player.Play and #targets > 0
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room:getAlivePlayers(false), function(p) return H.compareKingdomWith(p, player, true) end), Util.IdMapper)
    local tos = room:askForChoosePlayers(target, targets, 1, 1, "#ss_heg__jianzheng-choose", self.name, true)
    if #tos > 0 then
      local to = room:getPlayerById(tos[1])
      room:useVirtualCard("befriend_attacking", nil, target, to, self.name)
      room:setPlayerMark(target, "ss_heg__jianzheng-turn", 1)
      local isDeputy = H.inGeneralSkills(player, self.name)
      if isDeputy then
        room:setPlayerMark(player, "ss_heg__jianzheng_position-turn", isDeputy)
      end
    end
  end,
}

local jianzheng_delay = fk.CreateTriggerSkill{
  name = "#ss_heg__jianzheng_delay",
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    return player:usedSkillTimes(jianzheng.name, Player.HistoryTurn) > 0 and data.card.trueName == "slash" 
     and target:getMark("ss_heg__jianzheng-turn") > 0 and not player.dead and player:getMark("ss_heg__jianzheng_remove-turn") == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local isDeputy = player:getMark("ss_heg__jianzheng_position-turn")
    -- H.inGeneralSkills(player, jianzheng.name) 
    if isDeputy then
      H.removeGeneral(player.room, player, isDeputy == "d")
      player.room:setPlayerMark(player, "ss_heg__jianzheng_remove-turn", 1)
    end
  end,
}

zhuandui:addRelatedSkill(zhuandui_prohibit)
jianzheng:addRelatedSkill(jianzheng_delay)
qinmi:addSkill(zhuandui)
qinmi:addSkill(jianzheng)

Fk:loadTranslationTable{
  ["ss_heg__qinmi"] = "秦宓", --蜀国
  ["#ss_heg__qinmi"] = "彻天之舌", --蜀国
  ["designer:ss_heg__qinmi"] = "言喻",
  ["ss_heg__zhuandui"] = "专对",
  [":ss_heg__zhuandui"] = "锁定技，当你于回合内使用：首张牌时，所有角色本回合不能使用或打出点数小于此牌的牌；第二张牌时，若此牌的点数大于本回合上一张被使用的牌，你摸一张牌。",
  ["ss_heg__jianzheng"] = "谏征",
  [":ss_heg__jianzheng"] = "与你势力相同角色的出牌阶段开始时，你可令其选择是否视为使用一张【远交近攻】，若如此做，本回合其使用【杀】结算后，你移除此武将牌。",

  ["@ss_heg__zhuandui_forbidden-turn"] = "专对 限制",
  ["#ss_heg__jianzheng_delay"] = "谏征",
  ["#ss_heg__jianzheng-choose"] = "谏征：你可以视为对一名角色使用一张【远交近攻】",

  ["ss_heg__zhuandui1"] = "黄口小儿，也敢来班门弄斧？",
  ["ss_heg__zhuandui2"] = "你已无话可说了吧！",
  ["ss_heg__jianzheng1"] = "且慢，此仗打不得！",
  ["ss_heg__jianzheng2"] = "天时不当，必难取胜！",
  ["~ss_heg__qinmi"] = "我竟然，也百口莫辩了……",
}

local luoxian = General(extension, "ss_heg__luoxian", "shu", 4, 4, General.Male)
luoxian.hidden = true
local lixian = fk.CreateTriggerSkill{
  name = "ss_heg__lixian",
  anim_type = "special",
  events = {fk.EventPhaseStart, fk.EventPhaseChanging, fk.EventPhaseSkipped},
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and player == target) then return false end
    if event == fk.EventPhaseStart then
      return player.phase == Player.Finish and player.skipped_phases
    elseif event == fk.EventPhaseChanging then
      if data.to == Player.Judge then
        return table.every(player.room.alive_players, function(p) return player:getHandcardNum() <= p:getHandcardNum() end)
         or table.every(player.room.alive_players, function(p) return player.hp <= p.hp end)
      else
        return player:getMark("ss_heg__lixian_skip_last") == 1
      end
    else
      return true
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      return room:askForSkillInvoke(player, self.name, nil, "#ss_heg__lixian-drawcard")
    elseif event == fk.EventPhaseSkipped then
      return room:askForSkillInvoke(player, self.name, nil, "#ss_heg__lixian-skipnext")
    else
      if data.to == Player.Judge then
        return room:askForSkillInvoke(player, self.name, nil, "#ss_heg__lixian-skipjudge")
      else
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local n = 0
      for _, phase in ipairs({Player.Start, Player.Judge, Player.Draw, Player.Play, Player.Discard, Player.Finish}) do
        if player.skipped_phases[phase] then
          n = n + 1
        end
      end
      player:drawCards(n, self.name)
    elseif event == fk.EventPhaseSkipped then
      room:setPlayerMark(player, "ss_heg__lixian_skip_last", 1)
    else
      player:skip(data.to)
      room:setPlayerMark(player, "ss_heg__lixian_skip_last", 0)
      return true
    end
  end,
}

luoxian:addSkill(lixian)
Fk:loadTranslationTable{
  ["ss_heg__luoxian"] = "罗宪", --蜀国
  ["designer:ss_heg__luoxian"] = "QQ老冰",
  ["ss_heg__lixian"] = "历险",
  [":ss_heg__lixian"] = "①若你的手牌数或体力值为全场最小，你可跳过判定阶段；②当你跳过阶段后，你可跳过下一个阶段；③结束阶段，你可摸X张牌（X为你本回合跳过的阶段数）。",

  ["#ss_heg__lixian-drawcard"] = "历险：你可以摸你本回合跳过阶段数张牌",
  ["#ss_heg__lixian-skipnext"] = "历险：你可以跳过本回合下一个阶段",
  ["#ss_heg__lixian-skipjudge"] = "历险：你可以跳过判定阶段",

  ["~ss_heg__luoxian"] = "",
}

local ss_heg__chengpu = General:new(extension, "ss_heg__chengpu", "wu", 4, 4)
ss_heg__chengpu:addCompanions({ "hs__zhouyu" })

local ss__tongzheng = fk.CreateTriggerSkill {
  events = { fk.EventPhaseStart },
  name = "ss_heg__tongzheng",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target.phase == Player.Finish and H.compareKingdomWith(player, target) then
      local ids = {}
      player.room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
        for _, move in ipairs(e.data) do
          if move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonDiscard then
            for _, info in ipairs(move.moveInfo) do
              table.insertIfNeed(ids, info.cardId)
            end
          end
        end
        return false
      end, Player.HistoryTurn)
      ids = table.filter(ids, function(id) return player.room:getCardArea(id) == Card.DiscardPile end)
      self.cost_data = ids
      return #ids > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local ids = self.cost_data or {}
    if #ids > 0 then
      local invoke = room:askForSkillInvoke(player, self.name)
      if invoke then
      local get = room:askForCardsChosen(player, player, 1, 1, { card_data = { { "pile_discard", ids } } }, self.name, "#ss_heg__tongzheng-invoke")
        if #get > 0 then
          self.cost_data = get[1]
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cid = self.cost_data
    local c = Fk:getCardById(cid)
    local choices = {}
    local all_choices = { "#ss_heg__tongzheng-usec", "#ss_heg__tongzheng-givec" }
    if U.getDefaultTargets(target, c) then
      table.insert(choices, "#ss_heg__tongzheng-usec")
    end
    if target:isAlive() then
      table.insert(choices, "#ss_heg__tongzheng-givec")
    end
    if #choices > 0 then
      local choice = room:askForChoice(player, choices, self.name)
      if choice == "#ss_heg__tongzheng-usec" then
        U.askForUseRealCard(room, player, { cid }, ".", self.name, "#ss_heg__tongzheng-use:::" .. c:toLogString(), { expand_pile = { cid } }, false, false)
      else
        room:moveCardTo(cid, Player.Hand, target, fk.ReasonGive, self.name, nil, true, player.id)
      end
      if #room.logic:getActualDamageEvents(1, Util.TrueFunc, Player.HistoryTurn) == 0 and player:isAlive() then
        room:loseHp(player, 1, self.name)
      end
    end
  end,
}

ss_heg__chengpu:addSkill(ss__tongzheng)

Fk:loadTranslationTable {
  ["ss_heg__chengpu"] = "程普", -- 吴国
  ["designer:ss_heg__chengpu"] = "静谦",
  ["#ss_heg__chengpu"] = "铁脊灼江",
  ["cv:ss_heg__chengpu"] = "官方",
  ["illustrator:ss_heg__chengpu"] = "玖等仁品",

  ["ss_heg__tongzheng"] = "同征",
  [":ss_heg__tongzheng"] = "与你势力相同角色的结束阶段，你可选择一张本回合因弃置而进入弃牌堆的牌，使用之或将之交给该角色，然后若本回合没有角色受到过伤害，你失去1点体力。",

  ["#ss_heg__tongzheng-invoke"] = "同征：选择其中一张牌",
  ["#ss_heg__tongzheng-choice"] = "同征",
  ["#ss_heg__tongzheng-usec"] = "使用此牌",
  ["#ss_heg__tongzheng-givec"] = "将此牌交给当前回合角色",
  ["#ss_heg__tongzheng-use"] = "同征：请使用 %arg ",

  ["$ss_heg__tongzheng1"]="醇醪须与明君饮，沙场无还亦不悔。",
  ["$ss_heg__tongzheng2"]="醉里披甲执坚，梦中杀敌破阵。",
  ["~ss_heg__chengpu"] = "病疠缠身，终天命难违！",
}

local zhangwen = General(extension, "ss_heg__zhangwen", "wu", 3, 3, General.Male)
zhangwen.hidden = true
local songshu = fk.CreateTriggerSkill{
  name = "ss_heg__songshu",
}

local heyi = fk.CreateTriggerSkill{
  name = "ss_heg__heyi"
}
zhangwen:addSkill(songshu)
zhangwen:addSkill(heyi)
Fk:loadTranslationTable {
  ["ss_heg__zhangwen"] = "张温", -- 吴国
  ["designer:ss_heg__zhangwen"] = "",
  ["#ss_heg__zhangwen"] = "",
  ["illustrator:ss_heg__zhangwen"] = "官方",

  ["ss_heg__songshu"] = "颂蜀",
  [":ss_heg__songshu"] = "锁定技，①你的红色牌均视为拥有“合纵”标记；②当你因“合纵”摸牌时，你多摸一张牌；③其他角色因“合纵”摸牌时，若因此“合纵”获得牌的角色是你，其多摸一张牌",
  ["ss_heg__heyi"] = "合异",
  [":ss_heg__heyi"] = "锁定技，当你于出牌阶段内发动武将牌上“出牌阶段限一次”的技能或“合纵”后，你重新分配这些技能此阶段的可发动次数。",

  ["$ss_heg__songshu1"] = "",
  ["$ss_heg__songshu2"] = "",
  ["$ss_heg__heyi1"] = "",
  ["$ss_heg__heyi2"] = "",
  ["~ss_heg__zhangwen"] = "",
}

local liuyan = General(extension, "ss_heg__liuyan", "qun", 3, 3, General.Male)
liuyan.hidden = true
local jueguan_active = fk.CreateActiveSkill{
  name = "#ss_heg__jueguan_active",
  can_use = Util.FalseFunc,
  target_num = 0,
  card_filter = function(self, to_select, selected)
    if Fk:currentRoom():getCardArea(to_select) == Player.Equip then return end
    return table.every(selected, function (id) return Fk:getCardById(to_select).suit ~= Fk:getCardById(id).suit end)
  end,
}

local jueguan = fk.CreateTriggerSkill{
  name = "ss_heg__jueguan",
  events = {fk.EventPhaseStart},
  anim_type = "offensive",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Play
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local _, ret = room:askForUseActiveSkill(player, "#ss_heg__jueguan_active", "#ss_heg__jueguan-choose", false)
    local to_remain
    if ret then
      to_remain = ret.cards
    end
    player:showCards(to_remain)
    local suits = {}
    for _, id in ipairs(to_remain) do
      local card = Fk:getCardById(id)
      room:setCardMark(card, "@@ss_heg__jueguan-inhand-turn", 1)
      local suit = card.suit
      if suit ~= Card.NoSuit then
        table.insert(suits, suit)
      end
    end
    for _, p in ipairs(room.alive_players) do
      room:setPlayerMark(p, "ss_heg__jueguan_suit-phase", suits)
    end
  end,
}

local jueguan_maxcards = fk.CreateMaxCardsSkill{
  name = "#ss_heg__jueguan_maxcards",
  exclude_from = function(self, player, card)
    return player:hasSkill(jueguan.name) and card:getMark("@@ss_heg__jueguan-inhand-turn") > 0
  end,
}

local jueguan_prohibit = fk.CreateProhibitSkill{
  name = "#ss_heg__jueguan_prohibit",
  prohibit_use = function(self, player, card)
    local mark = player:getMark("ss_heg__jueguan_suit-phase")
    return type(mark) == "table" and table.contains(mark, card.suit)
  end,
}

local limu = fk.CreateTriggerSkill{
  name = "ss_heg__limu",
  events = {fk.EventPhaseStart},
  anim_type = "special",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Finish
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(room.alive_players, Util.IdMapper)
    if #targets == 0 then return end
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "#ss_heg__limu-choose", self.name, false)
    local to = room:getPlayerById(tos[1])
    local no_used_color = {"spade", "heart", "diamond", "club"}
    player.room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
      local use = e.data[1]
      if use.from == player.id and use.card.suit ~= Card.NoSuit then
        table.removeOne(no_used_color, use.card:getSuitString())
      end
    end, Player.HistoryTurn)
    if #room:askForDiscard(to, 1, 1, true, self.name, true, ".|.|" .. table.concat(no_used_color, ","), "#ss_heg__limu") == 0 then
      to:drawCards(4-#no_used_color, self.name)
      if H.hasGeneral(to, true) then
        H.removeGeneral(room, to, true)
        if not to.dead then
          to:gainAnExtraTurn(true, self.name)
        end
      end
    end
  end,
}

jueguan:addRelatedSkill(jueguan_active)
jueguan:addRelatedSkill(jueguan_maxcards)
jueguan:addRelatedSkill(jueguan_prohibit)
liuyan:addSkill(limu)
liuyan:addSkill(jueguan)

Fk:loadTranslationTable{
  ["ss_heg__liuyan"] = "刘焉", --群雄
  ["#ss_heg__liuyan"] = "裂土之宗", --群雄
  ["designer:ss_heg__liuyan"] = "静谦",
  ["ss_heg__jueguan"] = "绝关",
  [":ss_heg__jueguan"] = "出牌阶段开始时，你可以展示任意张花色各不相同的牌，令所有角色于此阶段内均不能使用这些花色的牌且这些牌本回合不计入你手牌上限。",
  ["ss_heg__limu"] = "立牧",
  [":ss_heg__limu"] = "结束阶段，你可以令一名角色选择一项：1.弃置一张你本回合未使用过的花色的牌；2.摸X张牌，然后移除副将并执行一个额外回合（X为你本回合使用过的花色数）。",

  ["jueguan"] = "绝关",
  ["@@ss_heg__jueguan-inhand"] = "绝关",
  ["ss_heg__jueguan_suit-phase"] = "绝关",
  ["@@ss_heg__jueguan-inhand-turn"] = "绝关",
  ["#ss_heg__jueguan_prohibit"] = "绝关",
  ["#ss_heg__jueguan_active"] = "绝关",
  ["#ss_heg__jueguan-choose"] = "绝关：选择任意张花色各不相同的牌",

  ["#ss_heg__limu-choose"] = "立牧：选择一名角色，令其弃置你本回合未使用花色的牌，或移除副将并执行一个额外的回合",
  ["#ss_heg__limu_filter"] = "立牧",
  ["#ss_heg__limu"] = "立牧：弃置一张本回合未使用花色的牌，或点“取消”摸牌移除副将并执行一个额外的回合",

  ["ss_heg__jueguan1"] = "非英杰不图？吾既谋之且射毕。",
  ["ss_heg__jueguan2"] = "汉室衰微，朝纲祸乱，必图后福。",
  ["ss_heg__limu1"] = "米贼作乱，吾必为益州自保。",
  ["ss_heg__limu2"] = "废史立牧，可得一方安定。",
  ["~ss_heg__liuyan"] = "背疮难治，世子难继。",
}


local hansui = General(extension, "ss_heg__hansui", "qun", 4, 4, General.Male)
local yaopan = fk.CreateTriggerSkill{
  name = "ss_heg__yaopan",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and target.phase == Player.Finish and target ~= player) then return false end
    local targets = {}
    player.room.logic:getActualDamageEvents(1, function(e)
      local damage = e.data[1]
      if player:distanceTo(damage.to) <= 1 and player:distanceTo(damage.to) >= 0 and not damage.to.chained and not damage.to.dead then
        table.insertIfNeed(targets, damage.to.id)
      end
      return false
    end)
    if #targets > 0 then
      self.cost_data = targets
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local tos = room:askForChoosePlayers(player, self.cost_data, 1, 1, "#ss_heg__yaopan-choose", self.name, false)
    local to = room:getPlayerById(tos[1])
    to:setChainState(true)
    local card_name = {"slash", "snatch"}
    room:setPlayerMark(to, "wk_heg__liance-phase", card_name)
    local success, dat = player.room:askForUseActiveSkill(to, "#wk_heg__liance_viewas", "#wk_heg__liance-choose", true)
    if success then
      local card = Fk.skills["#wk_heg__liance_viewas"]:viewAs(card_name)
        room:useCard{
        from = to.id,
        tos = table.map(dat.targets, function(id) return {id} end),
        card = card,
      }
    end
  end,
}

local hansui_mashu = fk.CreateDistanceSkill{
  name = "ss_heg__hansui__mashu",
  frequency = Skill.Compulsory,
  correct_func = function(self, from, to)
    if from:hasSkill(self) then
      return -1
    end
  end,
}

hansui:addCompanions("hs__mateng")
hansui:addSkill(yaopan)
hansui:addSkill(hansui_mashu)

Fk:loadTranslationTable{
  ["ss_heg__hansui"] = "韩遂", --群雄
  ["#ss_heg__hansui"] = "推关覆北", --群雄
  ["designer:ss_heg__hansui"] = "静谦",
  ["ss_heg__yaopan"] = "邀叛",
  [":ss_heg__yaopan"] = "其他角色的结束阶段，你可横置一名与你距离1以内且本回合受到过伤害的角色，然后其可视为使用一张【杀】或【顺手牵羊】。",
  ["ss_heg__hansui__mashu"] = "马术",
  [":ss_heg__hansui__mashu"] = "锁定技，你计算与其他角色的距离-1。",

  ["#ss_heg__yaopan-choose"] = "邀叛：选择一名与你距离1以内且本回合受到过伤害的角色",

  ["ss_heg__yaopan1"] = "（拔剑声）先吃我一剑！",
  ["ss_heg__yaopan2"] = "这是给你的下马威！",
  ["~ss_heg__hansui"] = "英雄一世，奈何祸起萧墙……",
}


--[[
Fk:loadTranslationTable{
  ["ss_heg__caoying"] = "曹婴", 
  ["#ss_heg__caoying"] = "见龙卸甲", 
  ["designer:ss_heg__hansui"] = "老猫",
  ["ss_heg__kunlong"] = "困龙",
  [":ss_heg__kunlong"] = "",
  ["ss_heg__fujian"] = "伏间,
  [":ss_heg__fujian"] = "",

  ["~ss_heg__caoying"] = "",
}

Fk:loadTranslationTable{
  ["ss_heg__chenshi"] = "陈式", 
  ["#ss_heg__chenshi"] = "", 
  ["designer:ss_heg__chenshi"] = "美丽",
  ["ss_heg__chenshi"] = "轻进",
  [":ss_heg__yaopan"] = "",
  
  ["~ss_heg__chenshi"] = "",
}

Fk:loadTranslationTable{
  ["ss_heg__xukun"] = "徐琨",
  ["#ss_heg__xukun"] = "", 
  ["designer:ss_heg__xukun"] = "烛台",
  ["ss_heg__fazhu"] = "筏铸",
  [":ss_heg__fazhu"] = "",
  
  ["~ss_heg__xukun"] = "",
}

Fk:loadTranslationTable{
  ["ss_heg__zhangrang"] = "张让", --群雄
  ["#ss_heg__zhangrang"] = "", --群雄
  ["designer:ss_heg__zhangrang"] = "老猫",
  ["ss_heg__danggu"] = "党锢",
  [":ss_heg__danggu"] = "",
  ["ss_heg__yating"] = "鸦庭",
  [":ss_heg__yating"] = "",

  ["~ss_heg__zhangrang"] = "",
}
--]]--
return extension
